package eu.dnetlib.openaire.usermanagement;

import com.unboundid.ldap.sdk.LDAPException;
import eu.dnetlib.openaire.user.utils.EmailSender;
import eu.dnetlib.openaire.user.utils.LDAPActions;
import eu.dnetlib.openaire.user.utils.VerificationActions;
import eu.dnetlib.openaire.user.utils.VerifyRecaptcha;
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.sql.Timestamp;
import java.util.Date;
import java.util.UUID;
/**
 * Created by kiatrop on 28/9/2017.
 */

public class ForgotPasswordServlet extends HttpServlet {

    @Autowired
    private LDAPActions ldapActions;

    @Autowired
    private VerificationActions verificationActions;

    @Autowired
    private EmailSender emailSender;

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

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

    private Logger logger = Logger.getLogger(ForgotPasswordServlet.class);

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

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

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


        if (formEmail == null) {
            request.getSession().setAttribute("message", "Error reading email.");
            response.sendRedirect("./forgotPassword.jsp");
        } else if (formEmail.isEmpty()) {
            request.getSession().setAttribute("message", "Please enter your email.");
            response.sendRedirect("./forgotPassword.jsp");
        } else if (!EmailValidator.getInstance().isValid(formEmail)) {
            request.getSession().setAttribute("message", "Please enter a valid email.");
            response.sendRedirect("./forgotPassword.jsp");
        } else if (!VerifyRecaptcha.verify(gRecaptchaResponse, secret)) {
            request.getSession().setAttribute("message", "You missed the reCAPTCHA validation!");
            response.sendRedirect("./forgotPassword.jsp");
        } else {
            try {
                String username = ldapActions.getUsername(formEmail);
                if (username == null || username.isEmpty()) {
                    request.getSession().setAttribute("message", "There is no user registered with that email.");
                    response.sendRedirect("./forgotPassword.jsp");
                } else {
                    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, "verify.jsp");
                    String resultPathWithVCode = UrlConstructor.getVerificationLink(resultPath, vCode);

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

                    String verificationCodeSubject = "Your OpenAIRE password reset request";

                    emailSender.sendEmail(formEmail, verificationCodeSubject, verificationCodeMsg);

                    response.setContentType("text/html");
                    response.sendRedirect("./verify.jsp");
                }

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