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

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.validators.TokenValidator;
import eu.eudat.logic.security.validators.orcid.helpers.ORCIDRequest;
import eu.eudat.logic.security.validators.orcid.helpers.ORCIDResponseToken;
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("orcidTokenValidator")
public class ORCIDTokenValidator implements TokenValidator {

	private ORCIDCustomProvider orcidCustomProvider;
	private Environment environment;
	private AuthenticationService nonVerifiedUserAuthenticationService;

	@Autowired
	public ORCIDTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, ORCIDCustomProvider orcidCustomProvider) {
		this.environment = environment;
		this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
		this.orcidCustomProvider = orcidCustomProvider;
	}

	@Override
	public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException {
		ORCIDUser orcidUser = new ORCIDUser().getOrcidUser(credentials.getData());
		LoginProviderUser user = new LoginProviderUser();
		user.setId(orcidUser.getOrcidId());
		user.setName(orcidUser.getName());
		user.setProvider(credentials.getProvider());
		user.setSecret(credentials.getTicket());
		return this.nonVerifiedUserAuthenticationService.Touch(user);
	}

	public ORCIDResponseToken getAccessToken(ORCIDRequest orcidRequest) {
		return this.orcidCustomProvider.getAccessToken(orcidRequest.getCode(), this.environment.getProperty("orcid.login.redirect_uri")
				, this.environment.getProperty("orcid.login.client_id")
				, this.environment.getProperty("orcid.login.client_secret"));
	}
}
