package eu.dnetlib.openaire.user.security;

import com.sun.org.apache.xpath.internal.SourceTree;
import org.apache.log4j.Logger;
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Date;

/**
 * Created by stefanos on 9/5/2017.
 */
public class FrontEndLinkURIAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

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

    private String frontEndURI;
    private String frontPath;
    private String frontDomain;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IllegalArgumentException, IOException   {

        OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication;

//        String uri = request.getScheme() + "://" +   // "http" + "://
//                request.getServerName() +       // "myhost"
//                ":" +                           // ":"
//                request.getServerPort() +       // "8080"
//                request.getRequestURI() +       // "/people"
//                "?" +                           // "?"
//                request.getQueryString();       // "lastname=Fox&age=30"
//
//        logger.info("\n++++++++++++++++++++++++++++++++++++++++++++++++++\n");
//
//        logger.info("uri: " + uri);
//
//        logger.info("\n++++++++++++++++++++++++++++++++++++++++++++++++++\n");

        try {

            Cookie jwt = new Cookie("XCsrfToken", JWTGenerator.generateToken(authOIDC, "my-very-secret"));
            Cookie accessToken = new Cookie("AccessToken", authOIDC.getAccessTokenValue());

            // Expire the cookies in four hours (4 * 3600)
            jwt.setMaxAge(14400);
            accessToken.setMaxAge(14400);

            //TODO DELETE LOG
            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
            logger.info("access token: " + authOIDC.getAccessTokenValue());
            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");

            jwt.setPath(frontPath);
            jwt.setDomain(frontDomain);
            accessToken.setPath(frontPath);
            accessToken.setDomain(frontDomain);

            response.addCookie(jwt);
            response.addCookie(accessToken);

//            logger.info("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
            //logger.info("parameter: " + request.getParameter("redirectUrl")); NULL
            //logger.info("parameter: " + request.getContextPath()); ONLY FIRST PATH
            //logger.info("parameter: " + request.getAttribute("redirectUrl")); NULL
            //logger.info("parameter: " + request.getRequestURI()); URL without parameter
            //logger.info("parameter: " + request.getQueryString()); code=33s9A8&state=212412fafacfd
            //logger.info("parameter: " + request.getContentType()); null
            //logger.info("parameter: " + request.getContentType());
//            String uri = request.getRequestURI();
//            if (request.getQueryString() != null)
//                uri += "?" + request.getQueryString();
//            logger.info("uri: " + uri);
//            logger.info("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
//            //response.sendRedirect(request.getParameter("redirectUrl"));
            response.sendRedirect(frontEndURI);


        } catch (IOException e) {
            logger.error("IOException in redirection ", e);
            throw new IOException(e);
        }catch (IllegalArgumentException e) {
            logger.error("IllegalArgumentException in redirection ", e);
            throw new IllegalArgumentException(e);
        }

    }

    public String getFrontEndURI() {
        return frontEndURI;
    }

    public void setFrontEndURI(String frontEndURI) {
        this.frontEndURI = frontEndURI;
    }

    public String getFrontPath() {
        return frontPath;
    }

    public void setFrontPath(String frontPath) {
        this.frontPath = frontPath;
    }

    public String getFrontDomain() {
        return frontDomain;
    }

    public void setFrontDomain(String frontDomain) {
        this.frontDomain = frontDomain;
    }
}


