package eu.dnetlib.openaire.usermanagement;

import eu.dnetlib.openaire.user.utils.InputValidator;
import eu.dnetlib.openaire.user.utils.LDAPActions;
import eu.dnetlib.openaire.user.utils.VerificationActions;
import eu.dnetlib.openaire.usermanagement.utils.UrlConstructor;
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.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;
import java.io.PrintWriter;

/**
 * Created by sofia on 23/10/2017.
 */
public class ActivationCodeServlet extends HttpServlet{

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

    @Autowired
    private VerificationActions verificationActions;

    @Autowired
    private LDAPActions ldapActions;

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

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

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

        String formUsername = request.getParameter("username").trim();
        String formVerificationCode = request.getParameter("verification_code").trim();

        if (InputValidator.isFilled(formUsername) && InputValidator.isFilled(formVerificationCode)) {
            if (verificationActions.verificationEntryExists(formUsername) && verificationActions.verificationCodeIsCorrect(formUsername, formVerificationCode)) {
                if (!verificationActions.verificationCodeHasExpired(formUsername)) {
                    HttpSession session = request.getSession();
                    session.setAttribute("username", formUsername);
                    session.setAttribute("homeUrl", oidcHomeUrl);
                    try {
                        ldapActions.moveUser(formUsername);
                    } catch (Exception e) {
                        logger.error("LDAP error in moving user", e);
                        response.sendRedirect(UrlConstructor.getRedirectUrl(request, "error.jsp"));
                    }
                    response.sendRedirect(UrlConstructor.getRedirectUrl(request, "registerSuccess.jsp"));
                } else {
                    logger.info("Verification code has expired!");
                    response.sendRedirect(UrlConstructor.getRedirectUrl(request, "expiredVerificationCode.jsp"));
                }
            } else {
                logger.info("Username or activation code are not valid!");
                request.getSession().setAttribute("message", "Username or activation code are not valid.");
                response.sendRedirect("./activate.jsp");
            }
        } else {
            if (!InputValidator.isFilled(formUsername)) {
                logger.info("No username");
                request.getSession().setAttribute("msg_username_error", "Please enter your username.");
            }
            if (!InputValidator.isFilled(formVerificationCode)) {
                logger.info("No activation code");
                request.getSession().setAttribute("msg_activation_code_error", "Please enter your activation code.");
            }
            response.sendRedirect("./activate.jsp");
        }
        printWriter.close();

    }

    public String getOidcHomeUrl() {
        return oidcHomeUrl;
    }

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