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.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.stereotype.Component;
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 javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by kiatrop on 2/10/2017.
 */
@Component
public class RemindUsernameServlet extends HttpServlet {

    @Autowired
    private LDAPActions ldapActions;

    @Autowired
    private EmailSender emailSender;

    @Value("${oidc.home}")
    private String oidcHomeUrl;

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

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

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

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

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String formEmail = request.getParameter("email").trim();

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

        HttpSession session = request.getSession();
        session.setAttribute("homeUrl", oidcHomeUrl);

        if (formEmail == null) {
            request.getSession().setAttribute("message", "Error reading email.");
            response.sendRedirect("./remindUsername.jsp");

        } else if (formEmail.isEmpty()) {
            request.getSession().setAttribute("message", "Please enter your email.");
            response.sendRedirect("./remindUsername.jsp");

        } else if (!EmailValidator.getInstance().isValid(formEmail)) {
            request.getSession().setAttribute("message", "Please enter a valid email.");
            response.sendRedirect("./remindUsername.jsp");

        } else if (!VerifyRecaptcha.verify(gRecaptchaResponse, secret)) {
            request.getSession().setAttribute("message", "You missed the reCAPTCHA validation!");
            response.sendRedirect("./remindUsername.jsp");

        } else {

            try {
                String username = ldapActions.getUsername(formEmail);
                if (username != null && !username.isEmpty()) {
                    logger.info("Remind username to: "+username);
                    String verificationCodeMsg = "<p>Hello,</p>" +
                            "<p> A username reminder has been requested for your OpenAIRE account.</p>" +
                            "<p> Your username is " + username + ".</p>" +
                            "<p> Thank you, </p>" +
                            "<p> OpenAIRE technical team</p>";

                    String verificationCodeSubject = "Your OpenAIRE username";

                    emailSender.sendEmail(formEmail, verificationCodeSubject, verificationCodeMsg);

                    response.sendRedirect(UrlConstructor.getRedirectUrl(request, "emailSuccess.jsp"));

                } else {
                    request.getSession().setAttribute("message", "There is no user registered with that email.");
                    response.sendRedirect("./remindUsername.jsp");
                }

            } catch (LDAPException ldape) {
                logger.error("Could not find user with email " + formEmail, 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(UrlConstructor.getRedirectUrl(request, "remindUsername.jsp"));
            }
        }
    }

    public String getOidcHomeUrl() {
        return oidcHomeUrl;
    }

    public void setOidcHomeUrl(String oidcHomeUrl) {
        this.oidcHomeUrl = oidcHomeUrl;
    }

}


