package eu.eudat.logic.security.validators.zenodo;

import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.logic.security.customproviders.ORCID.ORCIDCustomProvider;
import eu.eudat.logic.security.customproviders.ORCID.ORCIDUser;
import eu.eudat.logic.security.customproviders.Zenodo.ZenodoAccessType;
import eu.eudat.logic.security.customproviders.Zenodo.ZenodoCustomProvider;
import eu.eudat.logic.security.customproviders.Zenodo.ZenodoUser;
import eu.eudat.logic.security.validators.TokenValidator;
import eu.eudat.logic.security.validators.zenodo.helpers.ZenodoRequest;
import eu.eudat.logic.security.validators.zenodo.helpers.ZenodoResponseToken;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.loginprovider.LoginProviderUser;
import eu.eudat.models.data.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.GeneralSecurityException;

@Component("zenodoTokenValidator")
public class ZenodoTokenValidator implements TokenValidator {

	private ZenodoCustomProvider zenodoCustomProvider;
	private Environment environment;
	private AuthenticationService nonVerifiedUserAuthenticationService;

	@Autowired
	public ZenodoTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, ZenodoCustomProvider zenodoCustomProvider) {
		this.environment = environment;
		this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
		this.zenodoCustomProvider = zenodoCustomProvider;
	}

	@Override
	public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException {
		ZenodoUser zenodoUser = new ZenodoUser().getZenodoUser(credentials.getData());
		LoginProviderUser user = new LoginProviderUser();
		user.setId(zenodoUser.getUserId());
		user.setName(zenodoUser.getEmail());
		user.setEmail(zenodoUser.getEmail());
		user.setZenodoId(zenodoUser.getAccessToken());
		user.setZenodoExpire(zenodoUser.getExpiresIn());
		user.setZenodoRefresh(zenodoUser.getRefreshToken());
		user.setProvider(credentials.getProvider());
		user.setSecret(credentials.getTicket());
		return this.nonVerifiedUserAuthenticationService.Touch(user);
	}

	public ZenodoResponseToken getAccessToken(ZenodoRequest zenodoRequest) {
		return this.zenodoCustomProvider.getAccessToken(ZenodoAccessType.AUTHORIZATION_CODE, zenodoRequest.getCode()
				, this.environment.getProperty("zenodo.login.client_id")
				, this.environment.getProperty("zenodo.login.client_secret")
				, this.environment.getProperty("zenodo.login.redirect_uri"));
	}
}
