package nlib.cmm.web;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import nlib.bbs.service.ArticleVO;
import nlib.bbs.service.BoardService;
import nlib.bbs.service.QnaService;
import nlib.cmm.NlibCommonController;
import nlib.cmm.service.CodeService;
import nlib.cmm.service.MainService;
import nlib.cmm.service.NlibProperty;
import nlib.cmm.service.NotificationService;
import nlib.col.service.CartService;
import nlib.col.service.CollectionVO;
import nlib.util.StringUtil;

/**
 * <pre>
 * @Class Name : MainController.java
 * 
 * @Description : 메인화면에 표시할 정보를 처리하는 Controller 클래스
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 6. 22.    KNKIM       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP KNKIM
 * @since 2021. 6. 22.
 * @version 1.0
 *
 */
@Controller
public class MainController extends NlibCommonController {

	private static final Logger log = LoggerFactory.getLogger(MainController.class);
	
	@Resource(name="notificationService")
	private NotificationService notificationService; 

    @Resource(name = "cartService")
    private CartService cartService;

    @Resource(name = "codeService")
    private CodeService codeService;
    
    @Resource(name = "mainService")
    private MainService mainService;

	@Resource(name = "ancmntService")
	private BoardService ancmntService;

	@Resource(name = "qnaService")
	private QnaService qnaService;
	
	@RequestMapping( {"/index.do"} )
	public String setContent(
			HttpServletRequest request, 
			HttpServletResponse response, 
			Authentication authentication, 
			ModelMap model) throws Exception {

		// 캐쉬된 Reqeust 히스토리 삭제 
		RequestCache cache = new HttpSessionRequestCache();
		cache.removeRequest(request, response);
		
		String mngOrgCd = getCurCouncilCd(request);
		
		//------------------------------------------------
		// 추천 자료 관련 
		//------------------------------------------------
		
		// 추천키워드
		List<Map<String, String>> listKeywords = mainService.listKeywords(mngOrgCd);
		model.addAttribute("listKeywords", listKeywords);
		
		// 문화원 PICK
		model.addAttribute("mngOrgNm", getCurCouncilNm(request));
		model.addAttribute("listOrgPicks", mainService.listOrgPicks(mngOrgCd));
				
		// 유형별 인기자료 
		//List<Map<String, String>> listTypeDivCodes = codeService.listTypeDivCodes();
		//model.addAttribute("listTypeDivCodes", listTypeDivCodes);
		
		List<CollectionVO> listPops = mainService.listPops(mngOrgCd, null); // 전체 
		model.addAttribute("listPops", listPops);
		
		// 온라인자료관 
		model.addAttribute("listOnline", mainService.listOnline(mngOrgCd));
		
		//------------------------------------------------
		// 게시판관련 
		//------------------------------------------------
		ArticleVO searchArticleVO = new ArticleVO();
		searchArticleVO.setPageIndex(1);
		searchArticleVO.setPageSize(3);
		searchArticleVO.setMngOrgCd(getCurCouncilCd(request));
		
		// 공지사항 
		List<ArticleVO> listAncmnt = ancmntService.listArticles(searchArticleVO);
		model.addAttribute("listAncmnt", listAncmnt);
				
		// Q&A 
		String mbInfoId = getMbInfoId(request);
		searchArticleVO.setLoginedMbInfoId(mbInfoId);
		List<ArticleVO> listQna = qnaService.listArticles(searchArticleVO);
		model.addAttribute("listQna", listQna);
		
		// 메인 화면 배너 
		List<Map<String, String>> listBannerInfos = mainService.listBannerInfos(mngOrgCd);
		model.addAttribute("listBannerInfos", listBannerInfos);
		
		return "nlib/cmm/home";
	}

	@RequestMapping( {"/cmm/headerSubPart.do"} )
	public String headerSub(
			HttpServletRequest request, 
			HttpServletResponse response, 
			Authentication authentication, 
			ModelMap model) throws Exception {

		// 캐쉬된 Reqeust 히스토리 삭제 
		RequestCache cache = new HttpSessionRequestCache();
		cache.removeRequest(request, response);
		
		log.debug((authentication == null ? "손님 메인 접속" : authentication.getName() + " 메인 접속"));
		
		String mbInfoId = getMbInfoId(request);

		// 카트 건수 확인 
		int cartCnt = 0;
		if(StringUtil.isEmpty(mbInfoId)) {
			cartCnt = cartService.countCartItemsFromCookie(request, response, "1");
			cartCnt += cartService.countCartItemsFromCookie(request, response, "2");
		} else {
			cartCnt = cartService.countCartItems(mbInfoId, "0");
		}		
		
		// 알림 확인
		int unreadNotiCnt = 0;
		if(StringUtil.isNotEmpty(mbInfoId)) {
			unreadNotiCnt = notificationService.countUnreadNotification(mbInfoId);
		}
		
		if(!isAlerted(request)) {
			setAlerted(request, true);
		}
		
		model.addAttribute("cartCnt", cartCnt);
		model.addAttribute("unreadNotiCnt", unreadNotiCnt);
		model.addAttribute("docViewUrl", NlibProperty.getString("pdf.url"));
		model.addAttribute("videoViewUrl", NlibProperty.getString("video.url"));
		model.addAttribute("imageViewUrl", NlibProperty.getString("image.url"));
		
		return "nlib/cmm/headerSubPart";
	}
	
	@RequestMapping(value = "/main/bannerImage.do")
	public void getBannerImage(HttpServletRequest request, HttpServletResponse response, String bannerId) throws IOException {
		
		Map<String, String> bannerInfo = mainService.getBannerInfo(bannerId);
		boolean exists = false;
		
		if(bannerInfo != null && StringUtil.isNotEmpty(bannerInfo.get("fileStrePath")) && StringUtil.isNotEmpty(bannerInfo.get("streFileNm")) && StringUtil.isNotEmpty(bannerInfo.get("orignlFileNm"))) {
			try {
				String fileName = bannerInfo.get("fileStrePath") + bannerInfo.get("streFileNm");
				MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
				response.setContentType(mimetypesFileTypeMap.getContentType(bannerInfo.get("orignlFileNm")));
				response.getOutputStream().write(Files.readAllBytes(Paths.get(fileName)));
				exists = true;
			} catch(Exception e) {
				log.error("메인 화면 배너 관련 파일을 확인할 수 없습니다. : bannerId=" + bannerId);
			}
		}
		
		if(!exists) {
			try {
				String fileName = NlibProperty.getString("main.banner.img.path");
				MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
				response.setContentType(mimetypesFileTypeMap.getContentType(bannerInfo.get("orignlFileNm")));
				response.getOutputStream().write(Files.readAllBytes(Paths.get(fileName)));
				exists = true;
			} catch(Exception e) {
				log.error("메인 화면 배너 기본 배너 파일을 확인할 수 없습니다. : main.banner.img.path=" + NlibProperty.getString("main.banner.img.path"));
			}
		}
		
		return;
	}
	
}