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

import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
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 eu.eudat.logic.security.customproviders.B2Access.B2AccessCustomProvider;
import eu.eudat.logic.security.customproviders.B2Access.B2AccessUser;
import eu.eudat.logic.security.validators.TokenValidator;
import eu.eudat.logic.security.validators.b2access.helpers.B2AccessRequest;
import eu.eudat.logic.security.validators.b2access.helpers.B2AccessResponseToken;
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("b2AccessTokenValidator ")
public class B2AccessTokenValidator implements TokenValidator {

    private B2AccessCustomProvider b2AccessCustomProvider;
    private AuthenticationService nonVerifiedUserAuthenticationService;
    private Environment environment;

    @Autowired
    public B2AccessTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService, B2AccessCustomProvider b2AccessCustomProvider) {
        this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
        this.environment = environment;
        this.b2AccessCustomProvider = b2AccessCustomProvider;
    }

    @Override
    public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException {
        B2AccessUser b2AccessUser = this.b2AccessCustomProvider.getUser(credentials.getTicket());
        LoginProviderUser user = new LoginProviderUser();
        user.setId(b2AccessUser.getId());
        user.setEmail(b2AccessUser.getEmail());
        user.setName(b2AccessUser.getName());
        user.setProvider(credentials.getProvider());
        user.setSecret(credentials.getTicket());
        return this.nonVerifiedUserAuthenticationService.Touch(user);
    }

    public B2AccessResponseToken getAccessToken(B2AccessRequest b2AccessRequest) {
        return this.b2AccessCustomProvider.getAccessToken(b2AccessRequest.getCode(), this.environment.getProperty("b2access.externallogin.redirect_uri")
                , this.environment.getProperty("b2access.externallogin.clientid")
                , this.environment.getProperty("b2access.externallogin.clientSecret"));
    }
}
