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

import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
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 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;
import java.util.Collections;

@Component("googleTokenValidator")
public class GoogleTokenValidator implements TokenValidator {

	private static final HttpTransport transport = new NetHttpTransport();
	private AuthenticationService nonVerifiedUserAuthenticationService;
	private GoogleIdTokenVerifier verifier;

	@Autowired
	public GoogleTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService) {
		this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
		verifier = new GoogleIdTokenVerifier.Builder(transport, JacksonFactory.getDefaultInstance())
				.setAudience(Collections.singletonList(environment.getProperty("google.login.clientId")))
				.build();
	}

	private GoogleIdToken verifyUserAndGetUser(String idTokenString) throws IOException, GeneralSecurityException {
		return verifier.verify(idTokenString);
	}

	@Override
	public eu.eudat.models.data.security.Principal validateToken(LoginInfo credentials) throws IOException, GeneralSecurityException {
		GoogleIdToken idToken = this.verifyUserAndGetUser(credentials.getTicket());
		Payload payload = idToken.getPayload();
		LoginProviderUser user = new LoginProviderUser();
		user.setAvatarUrl((String) payload.get("picture"));
		user.setSecret(credentials.getTicket());
		user.setId(payload.getSubject());
		user.setProvider(TokenValidatorFactoryImpl.LoginProvider.GOOGLE);
		user.setName((String) payload.get("name"));
		user.setEmail(payload.getEmail());
		user.setIsVerified(payload.getEmailVerified());
		return this.nonVerifiedUserAuthenticationService.Touch(user);
	}
}
