package eu.eudat.controllers;


import eu.eudat.exceptions.security.ExpiredTokenException;
import eu.eudat.exceptions.security.NonValidTokenException;
import eu.eudat.exceptions.security.NullEmailException;
import eu.eudat.logic.managers.MetricsManager;
import eu.eudat.logic.managers.UserManager;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader;
import eu.eudat.logic.security.CustomAuthenticationProvider;
import eu.eudat.logic.security.customproviders.ConfigurableProvider.models.ConfigurableProvidersModel;
import eu.eudat.logic.security.validators.b2access.B2AccessTokenValidator;
import eu.eudat.logic.security.validators.b2access.helpers.B2AccessRequest;
import eu.eudat.logic.security.validators.b2access.helpers.B2AccessResponseToken;
import eu.eudat.logic.security.validators.configurableProvider.ConfigurableProviderTokenValidator;
import eu.eudat.logic.security.validators.configurableProvider.helpers.ConfigurableProviderRequest;
import eu.eudat.logic.security.validators.configurableProvider.helpers.ConfigurableProviderResponseToken;
import eu.eudat.logic.security.validators.linkedin.LinkedInTokenValidator;
import eu.eudat.logic.security.validators.linkedin.helpers.LinkedInRequest;
import eu.eudat.logic.security.validators.linkedin.helpers.LinkedInResponseToken;
import eu.eudat.logic.security.validators.openaire.OpenAIRETokenValidator;
import eu.eudat.logic.security.validators.openaire.helpers.OpenAIRERequest;
import eu.eudat.logic.security.validators.openaire.helpers.OpenAIREResponseToken;
import eu.eudat.logic.security.validators.orcid.ORCIDTokenValidator;
import eu.eudat.logic.security.validators.orcid.helpers.ORCIDRequest;
import eu.eudat.logic.security.validators.orcid.helpers.ORCIDResponseToken;
import eu.eudat.logic.security.validators.twitter.TwitterTokenValidator;
import eu.eudat.logic.security.validators.zenodo.ZenodoTokenValidator;
import eu.eudat.logic.security.validators.zenodo.helpers.ZenodoRequest;
import eu.eudat.logic.security.validators.zenodo.helpers.ZenodoResponseToken;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.login.Credentials;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.principal.PrincipalModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.MetricNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.social.oauth1.OAuthToken;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.io.IOException;
import java.security.GeneralSecurityException;


@RestController
@CrossOrigin
@RequestMapping(value = "api/auth")
public class Login {
    private static final Logger logger = LoggerFactory.getLogger(Login.class);

    private CustomAuthenticationProvider customAuthenticationProvider;
    private AuthenticationService nonVerifiedUserAuthenticationService;
    private TwitterTokenValidator twitterTokenValidator;
    private B2AccessTokenValidator b2AccessTokenValidator;
    private ORCIDTokenValidator orcidTokenValidator;
    private LinkedInTokenValidator linkedInTokenValidator;
    private OpenAIRETokenValidator openAIRETokenValidator;
    private ConfigurableProviderTokenValidator configurableProviderTokenValidator;
    private ZenodoTokenValidator zenodoTokenValidator;
    private ConfigLoader configLoader;
    private final MetricsManager metricsManager;

//    private Logger logger;

    private UserManager userManager;

    @Autowired
    public Login(CustomAuthenticationProvider customAuthenticationProvider,
                 AuthenticationService nonVerifiedUserAuthenticationService, TwitterTokenValidator twitterTokenValidator,
                 B2AccessTokenValidator b2AccessTokenValidator, ORCIDTokenValidator orcidTokenValidator,
                 LinkedInTokenValidator linkedInTokenValidator, OpenAIRETokenValidator openAIRETokenValidator,
                 ConfigurableProviderTokenValidator configurableProviderTokenValidator, ZenodoTokenValidator zenodoTokenValidator,
                 ConfigLoader configLoader, UserManager userManager,
                 MetricsManager metricsManager) {
        this.customAuthenticationProvider = customAuthenticationProvider;
        this.nonVerifiedUserAuthenticationService = nonVerifiedUserAuthenticationService;
        this.twitterTokenValidator = twitterTokenValidator;
        this.b2AccessTokenValidator = b2AccessTokenValidator;
        this.orcidTokenValidator = orcidTokenValidator;
        this.linkedInTokenValidator = linkedInTokenValidator;
        this.openAIRETokenValidator = openAIRETokenValidator;
        this.configurableProviderTokenValidator = configurableProviderTokenValidator;
        this.zenodoTokenValidator = zenodoTokenValidator;
        this.configLoader = configLoader;
        this.userManager = userManager;
        this.metricsManager = metricsManager;
    }


    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = {"/externallogin"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<PrincipalModel>> externallogin(@RequestBody LoginInfo credentials) throws GeneralSecurityException, NullEmailException {
        logger.info("Trying To Login With " + credentials.getProvider());
        metricsManager.increaseValue(MetricNames.USERS, 1, MetricNames.LOGGEDIN);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PrincipalModel>().payload(customAuthenticationProvider.authenticate(credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
    }

    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = {"/nativelogin"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<PrincipalModel>> nativelogin(@RequestBody Credentials credentials) throws NullEmailException {
        logger.info(credentials.getUsername() + " Trying To Login");
        metricsManager.increaseValue(MetricNames.USERS, 1, MetricNames.LOGGEDIN);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PrincipalModel>().payload(userManager.authenticate(this.nonVerifiedUserAuthenticationService, credentials)).status(ApiMessageCode.SUCCESS_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/twitterRequestToken"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<OAuthToken>> twitterRequestToken() {
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<OAuthToken>().payload(this.twitterTokenValidator.getRequestToken()).status(ApiMessageCode.NO_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/linkedInRequestToken"}, produces = "application/json", consumes = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<LinkedInResponseToken>> linkedInRequestToken(@RequestBody LinkedInRequest linkedInRequest) {
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<LinkedInResponseToken>().payload(this.linkedInTokenValidator.getAccessToken(linkedInRequest)).status(ApiMessageCode.NO_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/b2AccessRequestToken"}, produces = "application/json", consumes = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<B2AccessResponseToken>> b2AccessRequestToken(@RequestBody B2AccessRequest b2AccessRequest) {
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<B2AccessResponseToken>().payload(this.b2AccessTokenValidator.getAccessToken(b2AccessRequest)).status(ApiMessageCode.NO_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/orcidRequestToken"}, produces = "application/json", consumes = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<ORCIDResponseToken>> ORCIDRequestToken(@RequestBody ORCIDRequest orcidRequest) {
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ORCIDResponseToken>().payload(this.orcidTokenValidator.getAccessToken(orcidRequest)).status(ApiMessageCode.NO_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/openAireRequestToken"}, produces = "application/json", consumes = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<OpenAIREResponseToken>> openAIRERequestToken(@RequestBody OpenAIRERequest openAIRERequest) {
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<OpenAIREResponseToken>().payload(this.openAIRETokenValidator.getAccessToken(openAIRERequest)).status(ApiMessageCode.NO_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/configurableProviderRequestToken"}, produces = "application/json", consumes = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<ConfigurableProviderResponseToken>> configurableProviderRequestToken(@RequestBody ConfigurableProviderRequest configurableProviderRequest) {
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ConfigurableProviderResponseToken>().payload(this.configurableProviderTokenValidator.getAccessToken(configurableProviderRequest)).status(ApiMessageCode.NO_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/zenodoRequestToken"}, produces = "application/json", consumes = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<ZenodoResponseToken>> ZenodoRequestToken(@RequestBody ZenodoRequest zenodoRequest) {
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ZenodoResponseToken>().payload(this.zenodoTokenValidator.getAccessToken(zenodoRequest)).status(ApiMessageCode.NO_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/me"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<PrincipalModel>> authMe(Principal principal) throws NullEmailException {
        logger.info(principal + " Getting Me");
        Principal principal1 = this.nonVerifiedUserAuthenticationService.Touch(principal.getToken());
        PrincipalModel principalModel = PrincipalModel.fromEntity(principal1);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PrincipalModel>().payload(principalModel).status(ApiMessageCode.NO_MESSAGE));
    }

    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = {"/logout"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<Principal>> logout(Principal principal) {
        this.nonVerifiedUserAuthenticationService.Logout(principal.getToken());
        logger.info(principal + " Logged Out");
        metricsManager.decreaseValue(MetricNames.USERS, 1, MetricNames.LOGGEDIN);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Principal>().status(ApiMessageCode.NO_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/configurableLogin"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<ConfigurableProvidersModel>> getConfigurableProviders() {
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<ConfigurableProvidersModel>().payload(new ConfigurableProvidersModel().fromDataModel(configLoader.getConfigurableProviders())).status(ApiMessageCode.NO_MESSAGE));
    }
}
