package com.controller;

import com.constant.RegistrationErrorMsg;
import com.entity.Member;
import com.entity.SignInUser;
import com.entity.SignUpUser;
import com.service.RegistrationService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.sql.Date;
import java.sql.SQLException;

/**
 *
 * Rest controller for the Registration page.
 *
 * @author Laurentiu Marcut
 */
@Controller
public class RegistrationController {

    private static final Logger logger = Logger.getLogger(RegistrationController.class);

    private RegistrationService registrationService;

    @Autowired
    public RegistrationController(RegistrationService registrationService) {
        this.registrationService = registrationService;
    }

    /**
     *
     * Print welcome.
     *
     * @param model
     * @param request
     * @return response
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView printWelcome(ModelAndView model, HttpServletRequest request) {
        if (!"anonymousUser".equals(SecurityContextHolder.getContext().getAuthentication().getName())) {
            model.setViewName("redirect:/projects");
            logger.info("User " + request.getUserPrincipal().getName() + " is logged in. Redirect to the projects tab. ");
            return model;
        }

        model.addObject("signInUser", new SignInUser());
        model.addObject("signUpUser", new SignUpUser());
        model.setViewName("registration");
        return model;
    }

    /**
     *
     * Sign up the user.
     *
     * @param user
     * @param errors
     * @param model
     * @return response
     */
    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public ModelAndView processSignUp(@ModelAttribute @Valid SignUpUser user, Errors errors, ModelAndView model) {
        model.addObject("signInUser", new SignInUser());
        model.addObject("signUpUser", user);
        model.setViewName("registration");

        if (errors.hasErrors()) {
            return model;
        }

        if (!user.getPassword().equals(user.getRepeatPassword())) {
            errors.rejectValue("repeatPassword", "errors.user", RegistrationErrorMsg.PASSWORD_EQUALS);
            return model;
        }

        try {
            if (this.registrationService.checkEmail(user.getEmail())) {
                errors.rejectValue("email", "errors.user", RegistrationErrorMsg.EMAIL_EXISTS);
                return model;
            }
        } catch (SQLException e) {
            logger.error("Error in check the email " + user.getEmail(), e);
        }

        try {
            this.registrationService.insertUser(user);
        } catch (SQLException e) {
            logger.error("Error in insert the new user " + user.getEmail(), e);
        }

        logger.info("User " + user.getEmail() + " is successfull registered. ");
        model.addObject("signUpUser", new SignUpUser());
        model.addObject("registered", true);
        return model;
    }

    /**
     *
     * Log in the user.
     *
     * @param user
     * @param errors
     * @param model
     * @param logout
     * @param error
     * @return response
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView loginPage(@ModelAttribute SignInUser user, Errors errors, ModelAndView model,
                                  @RequestParam(value = "logout", required = false) String logout,
                                  @RequestParam(value = "error", required = false) String error) {

        model.addObject("signInUser", new SignInUser());
        model.addObject("signUpUser", new SignUpUser());
        model.setViewName("registration");

        if (logout != null) {
            model.addObject("logout", true);
        } else if (error != null) {
            errors.rejectValue("password", "error.user", RegistrationErrorMsg.ACCOUNT_INCORRECT);
            model.addObject("signInUser", user);
        }

        return model;
    }

}
