package kr.co.jinwoosi.clfd.clfd.site.service;

import kr.co.jinwoosi.clfd.clfd.user.service.ClfdUserService;
import kr.co.jinwoosi.clfd.conts.menu.model.Menu;
import kr.co.jinwoosi.clfd.conts.menu.model.MenuConnHist;
import kr.co.jinwoosi.clfd.conts.menu.service.MenuConnHistService;
import kr.co.jinwoosi.clfd.conts.menu.service.MenuService;
import kr.co.jinwoosi.clfd.conts.site.model.Site;
import kr.co.jinwoosi.clfd.conts.site.service.SiteService;
import kr.co.jinwoosi.clfd.framework.util.HttpUtil;
import kr.co.jinwoosi.clfd.framework.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Locale;

@Service
public class ClfdSiteService {

    @Resource (name="siteService")
    private SiteService siteService;

    @Resource (name="cmsMenuService")
    private MenuService menuService;

    @Resource (name="cmsMenuConnHistService")
    private MenuConnHistService menuConnHistService;

    @Autowired
    private ClfdUserService clfdUserService;

    public String visitClfdSite(HttpServletRequest request, HttpServletResponse response, Model model) {
        Site site = getSite(request, response, model);
        model.addAttribute("menuList", menuService.selectJson(site.getSiteId()));
        Menu menu = getMenu(site, request, model);
        return forwardMenu(site, menu, model, request);
    }

    private Site getSite(HttpServletRequest request, HttpServletResponse response, Model model) {
        Site result = null;

        if (request != null && response != null && model != null) {
            String servletPath = request.getServletPath();
            String domain = request.getServerName();
            if(request.getServerPort() != 80) {
                domain += ":"+request.getServerPort();
            }

            String[] urlArray = servletPath.split("/");
            String contextPath = urlArray[1];

            List<Site> siteList = siteService.selectJson();

            /* 멀티 사이트 */
            for(Site site : siteList) {
                String[] domainArray = site.getDomain().split(",");
                for(int i=0;i<domainArray.length;i++){
                    if(domain.equals(domainArray[i].trim()) && StrUtil.isEmpty(site.getStartUrl())) {
                        result = site;
                        break;
                    }
                }
            }

            for(Site site : siteList) {
                String[] domainArray = site.getDomain().split(",");
                for(int i=0;i<domainArray.length;i++){
                    /**
                     * 2021-02-15 홍석진
                     * 도메인이 '*' 일때는 도메인 판별 안하도록 변경
                     * 도메인 판별 기능은 보안을 위해 추후 사용
                     * ex) 도청내부에서만 접속 가능하도록 허용시킬 경우
                     *  **/
                    if (StringUtils.isEmpty(site.getDomain()) || site.getDomain().equals("*")) {
                        if(contextPath.equals(site.getStartUrl())) {
                            result = site;
                            break;
                        }
                    } else {
                        if(domain.equals(domainArray[i].trim()) && contextPath.equals(site.getStartUrl())) {
                            result = site;
                            break;
                        }
                    }
                }
            }

            //사이트에 설정 된 언어에 따라 Locale변경
            Locale locale = new Locale(result.getLang().getLangTp());
            LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
            localeResolver.setLocale(request, response, locale);

            //관련사이트 조회
            //RelSiteSearch relSiteSearch = new RelSiteSearch();
            //relSiteSearch.setSiteId (result.getSiteId ());
            //model.addAttribute ("relSite",relsiteService.selectList(relSiteSearch));

            model.addAttribute("currentSite", result);
            model.addAttribute("siteList", siteList);
        }
        return result;

    }

    private Menu getMenu(Site site, HttpServletRequest request, Model model) {
        Menu menu = null;

        if (request != null && model != null) {
            String servletPath = request.getServletPath();
            if(!StrUtil.isEmpty(site.getStartUrl())) servletPath = servletPath.substring(site.getStartUrl().length()+1);
            servletPath = servletPath.replace(".do", "");
            servletPath = servletPath.substring(1);

            menu = menuService.selectCurrentMenu(site.getSiteId(), servletPath);

            /**
             * 사이드 메뉴 정보 생성
             */
            model.addAttribute("sideMenu", menuService.selectParentMenu(site.getSiteId(), menu));
        }
        return menu;
    }

    private String forwardMenu(Site site, Menu menu, Model model, HttpServletRequest request) {
        String viewName = null;
        if (request != null && model != null) {
            model.addAttribute("menu", menu);
            //메뉴 접속 정보 저장
            MenuConnHist menuConnHist = new MenuConnHist();
            menuConnHist.setMenuId(menu.getMenuId());
            menuConnHist.setMenuConnIp(HttpUtil.getClientIp(request));
            menuConnHist.setRegId(clfdUserService.getUserId());
            menuConnHistService.insert(menuConnHist); //메뉴 접속 정보 저장
            System.out.println("menu.getMenuTp()=" + menu.getMenuTp());


            String startUrl = site.getStartUrl();

            if (startUrl.equals("clfd")) {
                // CLFD 사이트
                viewName = getClfdViewName(menu, startUrl);
            }
        }
        return viewName;
    }

    private String getClfdViewName(Menu menu, String startUrl) {
        /**
         * 2021-02-16 홍석진
         * 현재 clfd 사이트 메뉴 타입은 pgm만 사용
         */
        if("pgm".equals(menu.getMenuTp().trim())){
            if(menu.getUpperMenuId() != null){
                return startUrl +"/"+menu.getUpperMenu().getMenuUrl()+"/"+menu.getMenuUrl();
            }else{
                return startUrl + "/"+menu.getMenuUrl();
            }
        }
        return null;
    }
}
