package eu.eudat.controllers;

import eu.eudat.exceptions.emailconfirmation.HasConfirmedEmailException;
import eu.eudat.exceptions.emailconfirmation.TokenExpiredException;
import eu.eudat.logic.managers.EmailConfirmationManager;
import eu.eudat.logic.security.CustomAuthenticationProvider;
import eu.eudat.logic.services.operations.authentication.AuthenticationService;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.types.ApiMessageCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;

@RestController
@CrossOrigin
@RequestMapping(value = "api/emailConfirmation")
public class EmailConfirmation {

	private EmailConfirmationManager emailConfirmationManager;

	@Autowired
	public EmailConfirmation(EmailConfirmationManager emailConfirmationManager) {
		this.emailConfirmationManager = emailConfirmationManager;
	}

	@Transactional
	@RequestMapping(method = RequestMethod.GET, value = {"/{emailToken}"})
	public @ResponseBody
	ResponseEntity<ResponseItem> emailConfirmation(@PathVariable(value = "emailToken") String token) {
		try {
			this.emailConfirmationManager.confirmEmail(token);
			return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
		} catch
		(HasConfirmedEmailException | TokenExpiredException ex) {
			if (ex instanceof  TokenExpiredException) {
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE));
			} else {
				return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem().status(ApiMessageCode.WARN_MESSAGE));
			}
		}
	}

	@Transactional
	@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
	public @ResponseBody
	ResponseEntity sendConfirmatioEmail(@RequestBody String email, Principal principal) {
		try {
			this.emailConfirmationManager.sendConfirmationEmail(email, principal);
			return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
		} catch (Exception ex) {
			if (ex instanceof HasConfirmedEmailException) {
				return ResponseEntity.status(HttpStatus.FOUND).body(new ResponseItem().status(ApiMessageCode.WARN_MESSAGE));
			}
			return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE));
		}
	}
}
