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

import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.logic.security.customproviders.OpenAIRE.OpenAIRECustomProvider;
import eu.eudat.logic.security.customproviders.OpenAIRE.OpenAIREUser;
import eu.eudat.logic.security.validators.TokenValidator;
import eu.eudat.logic.security.validators.openaire.helpers.OpenAIRERequest;
import eu.eudat.logic.security.validators.openaire.helpers.OpenAIREResponseToken;
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.core.env.Environment;
import org.springframework.stereotype.Component;

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

@Component("openAIRETokenValidator")
public class OpenAIRETokenValidator implements TokenValidator {

	private Environment environment;
	private AuthenticationService nonVerifiedUserAuthenticationService;
	private OpenAIRECustomProvider openAIRECustomProvider;

	public OpenAIRETokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, OpenAIRECustomProvider openAIRECustomProvider) {
		this.environment = environment;
		this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
		this.openAIRECustomProvider = openAIRECustomProvider;
	}

	public OpenAIREResponseToken getAccessToken(OpenAIRERequest openAIRERequest) {
		return this.openAIRECustomProvider.getAccessToken(
				openAIRERequest.getCode(), this.environment.getProperty("openaire.login.redirect_uri"),
				this.environment.getProperty("openaire.login.client_id"), this.environment.getProperty("openaire.login.client_secret")
		);
	}

	@Override
	public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException {
		OpenAIREUser openAIREUser = this.openAIRECustomProvider.getUser(credentials.getTicket());
		LoginProviderUser user = new LoginProviderUser();
		user.setId(openAIREUser.getId());
		user.setEmail(openAIREUser.getEmail());
		user.setName(openAIREUser.getName());
		user.setProvider(credentials.getProvider());
		user.setSecret(credentials.getTicket());

		return this.nonVerifiedUserAuthenticationService.Touch(user);
	}
}
