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

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.facebook.api.User;
import org.springframework.social.facebook.connect.FacebookServiceProvider;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;


@Component("facebookTokenValidator")
public class FacebookTokenValidator implements TokenValidator {

	private AuthenticationService nonVerifiedUserAuthenticationService;
	private FacebookServiceProvider facebookServiceProvider;

	@Autowired
	public FacebookTokenValidator(Environment environment, AuthenticationService nonVerifiedUserAuthenticationService) {
		this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
		this.facebookServiceProvider = new FacebookServiceProvider(environment.getProperty("facebook.login.clientId"), environment.getProperty("facebook.login.clientSecret"), environment.getProperty("facebook.login.namespace"));
	}

	@Override
	public Principal validateToken(LoginInfo credentials) {
		User profile = getFacebookUser(credentials.getTicket());
		LoginProviderUser user = new LoginProviderUser();
		if (profile.getEmail() == null)
			throw new UnauthorisedException("Cannot login user.Facebook account did not provide email");

		user.setEmail(profile.getEmail());
		user.setId(profile.getId());
		//user.setIsVerified(profile.isVerified());
		user.setName(profile.getName());
		user.setProvider(TokenValidatorFactoryImpl.LoginProvider.FACEBOOK);
		String url = (String) ((Map<String, Object>) ((Map<String, Object>) profile.getExtraData().get("picture")).get("data")).get("url");
		user.setAvatarUrl(url);
		user.setSecret(credentials.getTicket());
		return this.nonVerifiedUserAuthenticationService.Touch(user);
	}


	private User getFacebookUser(String accessToken) {
		String[] fields = {"id", "email", "first_name", "last_name", "name", "verified", "picture"};
		return this.facebookServiceProvider.getApi(accessToken).fetchObject("me", User.class, fields);
	}

	private Date addADay(Date date) {
		Date dt = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(dt);
		c.add(Calendar.DATE, 1);
		dt = c.getTime();
		return dt;
	}
}
