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

import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.security.validators.TokenValidator;
import eu.eudat.logic.security.validators.TokenValidatorFactoryImpl;
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.social.oauth1.AuthorizedRequestToken;
import org.springframework.social.oauth1.OAuthToken;
import org.springframework.social.twitter.api.TwitterProfile;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
import org.springframework.social.twitter.connect.TwitterServiceProvider;
import org.springframework.stereotype.Component;

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


@Component("twitterTokenValidator")
public class TwitterTokenValidator implements TokenValidator {

    private Environment environment;
    private AuthenticationService nonVerifiedUserAuthenticationService;
    private TwitterServiceProvider twitterServiceProvider;

    @Autowired
    public TwitterTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService) {
        this.environment = environment;
        this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
        this.twitterServiceProvider = new TwitterServiceProvider(this.environment.getProperty("twitter.login.clientId"), this.environment.getProperty("twitter.login.clientSecret"));
    }

    @Override
    public Principal validateToken(LoginInfo credentials) throws NonValidTokenException, IOException, GeneralSecurityException, NullEmailException {
        String verifier = (String) ((Map)credentials.getData()).get("verifier");
        String email = (String) ((Map) credentials.getData()).get("email");
        OAuthToken oAuthToken = new OAuthToken(credentials.getTicket(), verifier);
        AuthorizedRequestToken authorizedRequestToken = new AuthorizedRequestToken(oAuthToken, verifier);
        OAuthToken finalOauthToken = this.twitterServiceProvider.getOAuthOperations().exchangeForAccessToken(authorizedRequestToken, null);
        TwitterTemplate twitterTemplate = new TwitterTemplate(this.environment.getProperty("twitter.login.clientId"), this.environment.getProperty("twitter.login.clientSecret"), finalOauthToken.getValue(), finalOauthToken.getSecret());
        TwitterProfile profile = this.twitterServiceProvider.getApi(finalOauthToken.getValue(), finalOauthToken.getSecret()).userOperations().getUserProfile();
        LoginProviderUser user = new LoginProviderUser();

        Map values = twitterTemplate.getRestTemplate().getForObject("https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true", Map.class);
        if (values.get("email") == null) {
//            throw new UnauthorisedException("Cannot login user.Twitter account did not provide email");
            user.setIsVerified(false); //TODO
            if (email != null && !email.isEmpty()) {
                user.setEmail(email);
            }
        }
        else {
            user.setEmail((String) values.get("email"));
            user.setIsVerified(true); //TODO
        }
        user.setAvatarUrl(profile.getProfileImageUrl());
        user.setId("" + profile.getId());
        user.setName(profile.getName());
        user.setProvider(TokenValidatorFactoryImpl.LoginProvider.TWITTER);
        user.setSecret(finalOauthToken.getValue());
        return this.nonVerifiedUserAuthenticationService.Touch(user);
    }

    public OAuthToken getRequestToken() {
        return this.twitterServiceProvider.getOAuthOperations().fetchRequestToken(this.environment.getProperty("twitter.login.redirect_uri"), null);
    }
}
