package eu.dnetlib.openaire.usermanagement;

import eu.dnetlib.openaire.user.utils.*;
import eu.dnetlib.openaire.usermanagement.utils.UrlConstructor;
import org.apache.commons.validator.routines.EmailValidator;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.mail.MessagingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;

/**
 * Created by sofia on 20/10/2017.
 */
public class RegisterServlet extends HttpServlet {

    @Autowired
    private VerificationActions verificationActions;

    @Autowired
    private EmailSender emailSender;

    @Autowired
    private LDAPActions ldapActions;

    @Value("${google.recaptcha.secret}")
    private String secret;

    @Value("${google.recaptcha.key}")
    private String sitekey;


    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
        config.getServletContext().setAttribute("sitekey", sitekey);
    }

    private static Logger logger = Logger.getLogger(RegisterServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        PrintWriter printWriter = response.getWriter();

        String firstName = request.getParameter("first_name").trim();
        String lastName = request.getParameter("last_name").trim();
        String organization = request.getParameter("organization").trim();
        String username = request.getParameter("username").trim();
        String email =request.getParameter("email").trim();
        String confirmEmail = request.getParameter("email_conf").trim();
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("password_conf");

        String gRecaptchaResponse = request.getParameter("g-recaptcha-response");

        boolean isRecaptchaVerified = VerifyRecaptcha.verify(gRecaptchaResponse, secret);
        ////System.out.println("RESPONSE " + gRecaptchaResponse);

        if (organization == null){
            logger.info("organization is null");
        }

        if (firstName != null && lastName != null &&  username != null && email!= null &&
                email.equals(confirmEmail) && password!= null && password.equals(confirmPassword) &&
                EmailValidator.getInstance().isValid(email) && InputValidator.isValidPassword(password) && isRecaptchaVerified) {

            try {
                 if (InputValidator.isValidUsername(username) && !ldapActions.usernameExists(username) && !ldapActions.emailExists(email)
                         && !ldapActions.isZombieUsersEmail(email) && !ldapActions.isZombieUsersUsername(username) && EmailValidator.getInstance().isValid(email)) {

                     ldapActions.createZombieUser(username, email, firstName, lastName, organization, password);
                     logger.info("Zombie user successfully created");

                     UUID verificationCode = UUID.randomUUID();
                     Date creationDate = new Date();
                     String vCode = verificationCode.toString();

                     Timestamp timestamp = new Timestamp(creationDate.getTime());

                     if (!verificationActions.verificationEntryExists(username)) {
                         verificationActions.addVerificationEntry(username, vCode, timestamp);

                     } else {
                         verificationActions.updateVerificationEntry(username, vCode, timestamp);
                     }

                     String resultPath = UrlConstructor.getRedirectUrl(request, "activate.jsp");
                     String resultPathWithVCode = UrlConstructor.getVerificationLink(resultPath, vCode);

                     String verificationCodeMsg = "<p>Hello " + username + ",</p>" +
                             "<p> A request has been made to verify your email and activate your OpenAIRE account. To activate your " +
                             "account, you will need to submit your username and this activation code in order to verify that the " +
                             "request was legitimate.</p>" +
                             "<p>" +
                             "The activation code is " + vCode +
                             "</p>" +
                             "Click the URL below and proceed with activating your password." +
                             "<p><a href=" + resultPathWithVCode + ">" + resultPathWithVCode + "</a></p>" +
                             "<p>The activation code is valid for 24 hours.</p>" +
                             "<p>Thank you,</p>" +
                             "<p>OpenAIRE technical team</p>";

                     String verificationCodeSubject = "Activate your OpenAIRE account";

                     emailSender.sendEmail(email, verificationCodeSubject, verificationCodeMsg);

                     response.sendRedirect("./activate.jsp");

                 } else {

                     validateUsername(request, username);

                     if (ldapActions.usernameExists(username) || ldapActions.isZombieUsersUsername(username)) {
                        request.getSession().setAttribute("username_message", "Username already exists! Choose another one.");
                        logger.info("Username already exists");
                     }

                     if (!EmailValidator.getInstance().isValid(email)) {
                         request.getSession().setAttribute("email_message", "Please enter a valid email.");
                         logger.info("Invalid email.");
                     }

                     if (ldapActions.emailExists(email)) {
                         request.getSession().setAttribute("email_message", "There is another user with this email.");
                         logger.info("There is another user with this email");
                     }

                     if (ldapActions.isZombieUsersEmail(email)) {
                         request.getSession().setAttribute("email_message", "You have already registered with this email address! Please check your email to activate your account or contact OpenAIRE <a href=\"https://www.openaire.eu/support/helpdesk\">helpdesk</a>.");
                         logger.info("There is another user with this email");
                     }

                     request.getSession().setAttribute("first_name", firstName);
                     request.getSession().setAttribute("msg_first_name_error_display", "display:none");

                     request.getSession().setAttribute("last_name", lastName);
                     request.getSession().setAttribute("msg_last_name_error_display", "display:none");

                     request.getSession().setAttribute("organization", organization);
                     request.getSession().setAttribute("username", username);
                     request.getSession().setAttribute("email", email);
                     request.getSession().setAttribute("msg_email_error_display", "display:none" );

                     request.getSession().setAttribute("email_conf", confirmEmail);
                     request.getSession().setAttribute("msg_email_conf_error_display", "display:none");
                     request.getSession().setAttribute("msg_email_validation_error_display", "display:none");

                     request.getSession().setAttribute("msg_password_error_display", "display:none" );
                     request.getSession().setAttribute("msg_pass_conf_error_display", "display:none" );
                     request.getSession().setAttribute("msg_invalid_password_display", "display:none");

                     request.getSession().setAttribute("recaptcha_error_display", "display:none");

                     response.sendRedirect("./register.jsp");
                 }


            } catch (MessagingException e) {
                logger.error("Error in sending email", e);
                request.getSession().setAttribute("message","Error sending email");
                response.sendRedirect(UrlConstructor.getRedirectUrl(request, ".register.jsp"));

                //TODO better handling of these exceptions
            } catch (Exception e) {
                logger.error("LDAP error in creating user", e);
                response.sendRedirect(UrlConstructor.getRedirectUrl(request, "error.jsp"));
            }

        } else {

            request.getSession().setAttribute("first_name", firstName);
            request.getSession().setAttribute("last_name", lastName);
            request.getSession().setAttribute("organization", organization);
            request.getSession().setAttribute("username", username);
            request.getSession().setAttribute("email", email);
            request.getSession().setAttribute("email_conf", confirmEmail);

            if (!InputValidator.isFilled(firstName)) {
                logger.info("No first name");
                request.getSession().setAttribute("msg_first_name_error_display", "display:block" );
            }

            if (!InputValidator.isFilled(lastName)) {
                logger.info("No last name");
                request.getSession().setAttribute("msg_last_name_error_display", "display:block" );
            }

            if (!InputValidator.isFilled(username)) {
                request.getSession().setAttribute("username_message", "Minimum username length 5 characters.");
                logger.info("No username");

            } else {
                validateUsername(request, username);
            }

            if (!InputValidator.isFilled(password)) {
                logger.info("No valid password");
                request.getSession().setAttribute("msg_password_error_display", "display:block" );
            }

            if(!EmailValidator.getInstance().isValid(email)) {
                logger.info("No valid e-mail");
                request.getSession().setAttribute("msg_email_validation_error_display", "display:block");
            }

            if (!email.equals(confirmEmail)) {
                logger.info("No matching e-mails");
                request.getSession().setAttribute("msg_email_conf_error_display", "display:block" );
            }

            if(!InputValidator.isValidPassword(password)) {
                logger.info("No valid password");
                request.getSession().setAttribute("msg_invalid_password_display", "display:block");
            }

            if (!password.equals(confirmPassword)){
                logger.info("No matching passwords");
                request.getSession().setAttribute("msg_pass_conf_error_display", "display:block" );
            }

            if (!isRecaptchaVerified) {
                logger.info("No valid recaptcha");
                request.getSession().setAttribute("recaptcha_error_display", "display:block" );
            }

            response.sendRedirect("./register.jsp");

        }

        printWriter.close();

    }

    private void validateUsername(HttpServletRequest request, String username) {

            if(!InputValidator.isValidUsername(username)) {
                logger.info("No valid username");

                if (InputValidator.containsLessCharsThan(5,username)) {
                    request.getSession().setAttribute("username_message", "Minimum username length 5 characters.");
                    logger.info("Minimum username length 5 characters.");
                }

                if (InputValidator.containsMoreCharsThan(150,username)) {
                    request.getSession().setAttribute("username_message", "Maximum username length 150 characters.");
                    logger.info("Maximum username length 150 characters.");
                }

                if (!InputValidator.containsOnlyAllowedChars(username)) {
                    request.getSession().setAttribute("username_allowed_chars_message", "You can use letters, numbers, underscores, hyphens and periods.");
                    logger.info("Only letters, numbers, underscores, hyphens and periods.");
                }

                if (!InputValidator.startsWithLetterOrDigit(username)) {
                    request.getSession().setAttribute("username_first_char_message", "The username must start with letter or digit.");
                    logger.info("The username must start with letter or digit.");
                }
            }
    }
}

