package org.slc.sli.admin.client;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import org.slc.sli.admin.util.URLHelper;
import org.slc.sli.admin.util.UrlBuilder;

/**
 * 
 * @author scole
 * 
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    
    private static final String SESSION_ID_KEY = "ADMIN_SESSION_ID";
    private static final String OPENAM_COOKIE_NAME = "iPlanetDirectoryPro";
    private static final String USER_NAME_KEY = "USER_NAME";
    
    private static Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);
    
    @Autowired
    private RESTClient restClient;
    
    public void setRESTClient(RESTClient rest) {
        this.restClient = rest;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object controller,
            Exception exception) throws Exception {
        
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
            throws Exception {
    }
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object sessionId = request.getSession().getAttribute(SESSION_ID_KEY);
        if (sessionId == null) {
            Cookie openAmCookie = WebUtils.getCookie(request, OPENAM_COOKIE_NAME);
            if (openAmCookie != null) {
                sessionId = openAmCookie.getValue();
                request.getSession().setAttribute(SESSION_ID_KEY, sessionId);
                request.getSession().setAttribute(USER_NAME_KEY, loadUserName((String) sessionId));
            } else {
                JsonObject jsonSession = this.restClient.sessionCheck(null);
                if (!jsonSession.get("authenticated").getAsBoolean()) {
                    String baseUrl = jsonSession.get("redirect_user").getAsString();
                    String requestedURL = URLHelper.getUrl(request);
                    logger.debug("Using return URL of: " + requestedURL);
                    UrlBuilder url = new UrlBuilder(baseUrl);
                    url.addQueryParam("RelayState", requestedURL);
                    response.sendRedirect(url.toString());
                }
                return false;
            }
        }
        return true;
    }
    
    private String loadUserName(String token) {
        JsonObject json = this.restClient.sessionCheck(token);
        JsonElement authoritiesElement = json.get("granted_authorities");
        if (authoritiesElement != null) {
            JsonArray authorities = authoritiesElement.getAsJsonArray();
            JsonElement authorityElement = authorities.get(0);
            if (authorityElement != null) {
                JsonElement nameElement = authorityElement.getAsJsonObject().get("authority");
                return nameElement.getAsString();
            }
        }
        return "";
    }
}

@@ -160,42 +160,8 @@
 e;%0A%0A
-import com.google.gson.JsonArray;%0A
 impo
@@ -3006,27 +3006,20 @@
 Element 
-authorities
+name
 Element 
@@ -3034,352 +3034,56 @@
 et(%22
-granted_authorities%22);%0A        if (authoritiesElement != null) %7B%0A            JsonArray authorities = authoritiesElement.getAsJsonArray();%0A            JsonElement authorityElement = authorities.get(0);%0A            if (authorityElement != null) %7B%0A                JsonElement nameElement = authorityElement.getAsJsonObject().get(%22authority%22);%0A    
+full_name%22);%0A        if (nameElement != null) %7B%0A
     
@@ -3124,30 +3124,16 @@
 ring();%0A
-            %7D%0A
         

fix username display