/*
 * Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 

package org.maxkey.web.interceptor;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import org.apache.tomcat.util.http.LegacyCookieProcessor;
import org.maxkey.authn.AbstractAuthenticationProvider;
import org.maxkey.authn.LoginCredential;
import org.maxkey.authn.SavedRequestAwareAuthenticationSuccessHandler;
import org.maxkey.authn.SigninPrincipal;
import org.maxkey.authn.online.OnlineTicket;
import org.maxkey.authn.online.OnlineTicketServices;
import org.maxkey.configuration.ApplicationConfig;
import org.maxkey.constants.ConstantsLoginType;
import org.maxkey.constants.ConstantsPasswordSetType;
import org.maxkey.constants.ConstantsTimeInterval;
import org.maxkey.entity.UserInfo;
import org.maxkey.persistence.redis.RedisConnection;
import org.maxkey.persistence.redis.RedisConnectionFactory;
import org.maxkey.web.WebConstants;
import org.maxkey.web.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import static org.maxkey.web.WebContext.getRequest;

/**
 * 权限Interceptor处理 权限处理需在servlet.xml中配置 mvc:interceptors permission
 * 
 * @author Crystal.Sea
 *
 */
@Component
public class PermissionAdapter  implements AsyncHandlerInterceptor  {
    private static final Logger _logger = LoggerFactory.getLogger(PermissionAdapter.class);
    // 无需Interceptor url
    @Autowired
    @Qualifier("applicationConfig")
    private ApplicationConfig applicationConfig;

    @Autowired
    @Qualifier("authenticationProvider")
    AbstractAuthenticationProvider authenticationProvider;


    @Autowired
    RedisConnectionFactory redisConnectionFactory;


    @Autowired
    @Qualifier("savedRequestSuccessHandler")
    SavedRequestAwareAuthenticationSuccessHandler savedRequestSuccessHandler;
    
    static ConcurrentHashMap<String, String> navigationsMap = null;
    
    @Autowired
    @Qualifier("onlineTicketServices")
    protected OnlineTicketServices onlineTicketServices;

    /*
     * 请求前处理 (non-Javadoc)
     * 
     * @see
     * org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(
     * javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object)
     */

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AsyncHandlerInterceptor.super.afterCompletion(request, response, handler, ex);

    }

    @Override
    public boolean preHandle(HttpServletRequest request, 
            HttpServletResponse response, Object handler)
            throws Exception {
        _logger.error("PermissionAdapter preHandle");
        _logger.error("PermissionAdapter " + request.getSession().getId());
        Object passwordSetTypeAttribute=WebContext.getSession().getAttribute(WebConstants.CURRENT_USER_PASSWORD_SET_TYPE);
        ModifyHttpServletRequestWrapper mParametersWrapper = new ModifyHttpServletRequestWrapper(request);
//        String token = request.getHeader("token");
//        if (token != null && !"".equals(token)) {
//            mParametersWrapper.putCookie("JSESSIONID", token);
//        }

        response.addHeader("P3P", "CP='CAO PSA OUR'");

        _logger.error("-----------------------------");
        _logger.error(request.getRequestURI());
        _logger.error("-----------------------------");
        String s = request.getParameter("sid");
        if(s!=null){


            try{
                RedisConnection redisConnection = redisConnectionFactory.getConnection();
                String userInfo1 = (String) redisConnection.get(s);
                redisConnection.close();
                _logger.error(userInfo1);
                UserInfo userInfo = JSON.parseObject(userInfo1,UserInfo.class);
                LoginCredential loginCredential = new LoginCredential(
                        userInfo.getUsername(), "", ConstantsLoginType.JWT);

                WebContext.setUserInfo(userInfo);
                WebContext.setAuthentication(authenticationProvider.authentication(loginCredential, true));


                Authentication authentication = WebContext.getAuthentication();
                _logger.error(JSON.toJSONString(authentication));

//                RequestCache requestCache = new HttpSessionRequestCache();
//                requestCache.saveRequest(request, response);
//                SavedRequest  savedRequest =requestCache.getRequest(request, response);
//                WebContext.setAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER,savedRequest);


            }catch (Exception e){

               e.printStackTrace();
            }




//            mParametersWrapper.putCookie("JSESSIONID", s);
//            _logger.error("-----------------------------");
//            _logger.error(JSON.toJSONString(mParametersWrapper.getCookies()));
//            _logger.error("-----------------------------");

//            Cookie cookie=new Cookie("JSESSIONID",s);
//            cookie.setPath("/");
//            cookie.setHttpOnly(true);
//            cookie.setDomain("wenhq.top");
//            response.addCookie(cookie);
//
//            Cookie cookie1=new Cookie("JSESSIONID",s);
//            cookie1.setPath("/taihu-auth");cookie1.setHttpOnly(true);
//            cookie1.setDomain(request.getServerName());
//            response.addCookie(cookie1);
//
//            Cookie cookie2=new Cookie("JSESSIONID",s);
//            cookie2.setPath("/taihu-auth");
//            cookie2.setDomain("thauth.xt.wenhq.top");cookie2.setHttpOnly(true);
//            response.addCookie(cookie2);

//            response.addHeader("Set-Cookie", "JSESSIONID="+s+"; Path=/taihu-auth;");




//            WebContext.setCookie(response,null, "JSESSIONID", s, ConstantsTimeInterval.ONE_WEEK);
//            WebContext.setCookie(response,"/taihu-auth", "JSESSIONID", s, ConstantsTimeInterval.ONE_WEEK);
        }



        if(passwordSetTypeAttribute != null) {
            Integer passwordSetType=(Integer)passwordSetTypeAttribute;
            if(passwordSetType==ConstantsPasswordSetType.PASSWORD_EXPIRED||
                    passwordSetType==ConstantsPasswordSetType.MANAGER_CHANGED_PASSWORD){
                _logger.trace("changeExpiredPassword ... forward to /safe/changeExpiredPassword");
                if(request.getRequestURI().indexOf("/changeExpiredPassword")>-1) {
                    return true;
                }
                RequestDispatcher dispatcher = request.getRequestDispatcher("/safe/changeExpiredPassword");
                dispatcher.forward(mParametersWrapper, response);
                return false;
            }else if(passwordSetType==ConstantsPasswordSetType.INITIAL_PASSWORD){
                _logger.trace("changeInitPassword ... forward to /safe/changeInitPassword");
                if(request.getRequestURI().indexOf("/changeInitPassword")>-1) {
                    return true;
                }
                RequestDispatcher dispatcher = request.getRequestDispatcher("/safe/changeInitPassword");
                dispatcher.forward(mParametersWrapper, response);
                return false;
            }
        }
        
        Authentication authentication = WebContext.getAuthentication();
        //save  first protected url 
        SavedRequest  firstSavedRequest = (SavedRequest)WebContext.getAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
        // 判断用户是否登录, 判断用户和角色，判断用户是否登录用户
        if  (authentication == null 
                || authentication.getAuthorities() == null) {
            //保存未认证的请求信息
            if(firstSavedRequest==null){
                RequestCache requestCache = new HttpSessionRequestCache();
                requestCache.saveRequest(request, response);
                SavedRequest  savedRequest =requestCache.getRequest(request, response);
                if(savedRequest!=null){
                    _logger.debug("first request parameter  savedRequest "+savedRequest.getRedirectUrl());
                    WebContext.setAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER, savedRequest);
                    savedRequestSuccessHandler.setRequestCache(requestCache);
                }
            }
            
            _logger.trace("No Authentication ... forward to /login");
            RequestDispatcher dispatcher = request.getRequestDispatcher("/login");
            dispatcher.forward(mParametersWrapper, response);
            return false;
        }
        
        
        //认证完成，跳转到未认证请求
        if(firstSavedRequest!=null) {
            savedRequestSuccessHandler.onAuthenticationSuccess(request, response, authentication);
            WebContext.removeAttribute(WebConstants.FIRST_SAVED_REQUEST_PARAMETER);
        }

        boolean hasAccess = true;
        
        try {
	        if(authentication.getPrincipal() instanceof SigninPrincipal) {
	            SigninPrincipal signinPrincipal = (SigninPrincipal)authentication.getPrincipal();
	            //if onlineTicket refresh is removed or timeout then Exception 
	            OnlineTicket onlineTicket = signinPrincipal.getOnlineTicket();
	            onlineTicketServices.refresh(onlineTicket.getTicketId());
	        }
        }catch(Exception e) {
            _logger.debug("Online Ticket timeout ... forward to /login");
        	RequestDispatcher dispatcher = request.getRequestDispatcher("/logout");
        	dispatcher.forward(mParametersWrapper, response);
        }
        /*
         * boolean preHandler = super.preHandle(request, response, handler);
         * 
         * if(preHandler) { preHandler = false;
         * 
         * 
         * if(!preHandler){//无权限转向
         * log.debug("You do not have permission to access "+accessUrl);
         * RequestDispatcher dispatcher = request.getRequestDispatcher("/accessdeny");
         * dispatcher.forward(request, response); return false; } }
         */
        return hasAccess;
    }

    private class ModifyHttpServletRequestWrapper extends HttpServletRequestWrapper {
        private Map<String, String> mapCookies;
        ModifyHttpServletRequestWrapper(HttpServletRequest request) {
            super(request);
            this.mapCookies = new HashMap<>();
        }
        void putCookie(String name, String value) {
            this.mapCookies.put(name, value);
        }
        public Cookie[] getCookies() {
            HttpServletRequest request = (HttpServletRequest) getRequest();
            Cookie[] cookies = request.getCookies();
            if (mapCookies == null || mapCookies.isEmpty()) {
                return cookies;
            }
            if (cookies == null || cookies.length == 0) {
                List<Cookie> cookieList = new LinkedList<>();
                for (Map.Entry<String, String> entry : mapCookies.entrySet()) {
                    String key = entry.getKey();
                    if (key != null && !"".equals(key)) {
                        cookieList.add(new Cookie(key, entry.getValue()));
                    }
                }
                if (cookieList.isEmpty()) {
                    return cookies;
                }
                return cookieList.toArray(new Cookie[cookieList.size()]);
            } else {
                List<Cookie> cookieList = new ArrayList<>(Arrays.asList(cookies));
                for (Map.Entry<String, String> entry : mapCookies.entrySet()) {
                    String key = entry.getKey();
                    if (key != null && !"".equals(key)) {
                        for (int i = 0; i < cookieList.size(); i++) {
                            if(cookieList.get(i).getName().equals(key)){
                                cookieList.remove(i);
                            }
                        }
                        cookieList.add(new Cookie(key, entry.getValue()));
                    }
                }
                return cookieList.toArray(new Cookie[cookieList.size()]);
            }
        }
    }

    @Bean
    public WebServerFactoryCustomizer<TomcatServletWebServerFactory> cookieProcessorCustomizer() {
        return (factory) -> factory.addContextCustomizers(
                (context) -> context.setCookieProcessor(new LegacyCookieProcessor()));
    }
}

