package motoSample;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;

import java.util.Map;
import java.util.logging.Logger;
import java.io.PrintWriter;
import java.io.IOException;

import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.message.ParameterList;

public class OpenIdReturn extends HttpServlet {
    private static Logger log = Logger.getLogger(OpenIdReturn.class.getName());

    public OpenIdReturn() {
        super();
    }
    
    static Identifier returnCheck(DiscoveryInformation discoveryInformation, Map pageParameters, String returnToUrl) {
        ParameterList response = new ParameterList(pageParameters);
        try {
            VerificationResult verificationResult = OpenIdBean.getConsumerManager().verify(returnToUrl, response, discoveryInformation);
            Identifier verifiedIdentifier = verificationResult.getVerifiedId();
            return verifiedIdentifier;
        } catch (Exception e) {
            String message = "Exception occurred while verifying response!";
            log.severe(message);
            throw new RuntimeException(message, e);
        }
    }

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

        HttpSession session = request.getSession();
        DiscoveryInformation di = (DiscoveryInformation) session.getAttribute("discoveryInformation");

        Identifier id = returnCheck(di, request.getParameterMap(), OpenIdBean.getReturnUrl());
        session.removeAttribute("discoveryInformation");
        
        PrintWriter out = response.getWriter();
        UserBean ubean = (UserBean)session.getAttribute("userBean");

        out.println("<HTML><HEAD><TITLE>open id login page</TITLE></HEAD>");
        out.println("<BODY>");

        if (id == null) {
            out.println("<H3>open id verification failure...</H3>");
        }
        else {
            String openid = id.getIdentifier();
            String nextUrl = ubean.doOpenIdLogin(openid, session);
            if (nextUrl == null) {
                out.println("Open ID : <H3>" + openid + "</H3> not found...");
            }
            else {
                out.println("open id login ok. log in user : <H3>" + ubean.getUname()+ "</H3>.");
                String contextPath = request.getContextPath();
                /*log.info("contextPath: " + contextPath);
                log.info("last char: " + contextPath.charAt(contextPath.length() -  1));
                if (contextPath.charAt(contextPath.length() -  1) != '/')
                    contextPath += "/";
                */
                response.sendRedirect(contextPath + nextUrl);
            }
        }
        out.println("</BODY>");
        out.println("</HTML>");
    }

}
