package eu.eudat.logic.security;

import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.principal.PrincipalModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.logic.security.validators.TokenValidatorFactory;
import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
import net.shibboleth.utilities.java.support.resolver.ResolverException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class CustomAuthenticationProvider {
    private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);


    @Autowired
    private TokenValidatorFactory tokenValidatorFactory;

    public PrincipalModel authenticate(LoginInfo credentials) throws GeneralSecurityException, NullEmailException {
        String token = credentials.getTicket();
        try {
            Principal principal = this.tokenValidatorFactory.getProvider(credentials.getProvider()).validateToken(credentials);
            return (principal != null) ? PrincipalModel.fromEntity(principal) : null;
        } catch (NonValidTokenException e) {
            logger.error("Could not validate a user by his token! Reason: " + e.getMessage(), e);
            throw new UnauthorisedException("Token validation failed - Not a valid token");
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new UnauthorisedException("IO Exeption");
        } catch (NullEmailException e) {
            logger.error(e.getMessage(), e);
            throw new NullEmailException();
        } catch (ResolverException | ComponentInitializationException e){
            logger.error(e.getMessage(), e);
            throw new GeneralSecurityException();
        }
    }
}