package com.style24.scm.biz.web;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.User;
import com.style24.scm.biz.service.TssLoginService;
import com.style24.scm.biz.service.TssNoticeService;
import com.style24.scm.support.controller.TssBaseController;
import com.style24.scm.support.security.session.TssSession;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.rest.server.GagaResponse;
import com.gagaframework.web.security.GagaPasswordEncoder;

/**
 * Index Controller
 * 
 * @author gagamel
 * @since 2020. 10. 19
 */
@Controller
@Slf4j
public class TssIndexController extends TssBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TssLoginService loginService;

	@Autowired
	private GagaPasswordEncoder passwordEncoder;

	@Autowired
	private TssNoticeService noticeService;

	@Autowired
	private Environment env;

	/**
	 * 첫 페이지
	 * 		로그인 하고
	 * 			2factor인증까지 되었으면 대쉬보드 화면으로 이동하고
	 * 			아니면 2factor인증 화면으로
	 * 		아니면 로그인 페이지로
	 * @param isError - 오류여부(true/false)
	 * @param session - HttpSession
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 19
	 */
	@GetMapping({"/", "/index"})
	public ModelAndView index(@RequestParam(value = "error", required = false) boolean isError, HttpSession session) {
		ModelAndView mav = new ModelAndView();

		if (TssSession.isLogin()) {
			if (TssSession.isTwoFactorCertify()) { // 2factor인증이 되었으면
				// 공지사항 팝업 총건수
				mav.addObject("noticeCnt", noticeService.getNoticePopupTotalCount());

				// 대쉬보드 페이지로
				mav.setViewName("dashboard");
			} else {
				// 운영서버에서만 2factor인증 진행
				if ("run".equals(env.getProperty("spring.profiles.active")) || "style".equals(env.getProperty("spring.profiles.active"))) {
					// 2factor인증번호 발송
					loginService.sendTwoFactorCertNo();

					// 2factor인증 페이지로
					mav.setViewName("signin2");
				} else {
					// 대쉬보드 페이지로
					mav.setViewName("dashboard");
				}
			}
			return mav;
		}

		log.info("isError: {}", isError);
		if (isError) {
			Exception e = (Exception)session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
			log.info("e.getMessage(): {}", e.getMessage());
			mav.addObject("error", e.getMessage());
		}

		// 로그인 페이지로
		mav.setViewName("signin");

		return mav;
	}

	/**
	 * 2factor인증번호가 맞는지 확인
	 * @param certNo - 인증번호
	 * @return ture/false
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@GetMapping("/tfcertify/check/{certNo}")
	@ResponseBody
	public boolean isTwoFactorCertify(@PathVariable("certNo") String certNo) {
		if (certNo.equals(TssSession.getAttribute("tfcertno"))) {
			TssSession.setAttribute("isTfcertify", "true");
			TssSession.setAttribute("tfcertno", "");
			return true;
		}

		return false;
	}

	/**
	 * 2factor인증번호 발송
	 * @return
	 * @author gagamel
	 * @since 2020. 10. 7
	 */
	@PostMapping("/tfcertify/send")
	@ResponseBody
	public GagaResponse sendCertNo() {
		loginService.sendTwoFactorCertNo();
		return super.ok(message.getMessage("SUCC_0005"));
	}

	/**
	 * 비밀번호 변경 팝업
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 28
	 */
	@GetMapping("/password/change/form")
	public ModelAndView passwordChangeForm() {
		ModelAndView mav = new ModelAndView();

		mav.setViewName("PasswordChangeForm");

		return mav;
	}

	/**
	 * 비밀번호 변경 처리
	 * @param user - 사용자 정보
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 28
	 */
	@PostMapping("/password/change")
	@ResponseBody
	public GagaResponse changePassword(@RequestBody User user) {
		user.setUserNo(TssSession.getInfo().getUserNo());
		user.setPasswd(passwordEncoder.encode(user.getPasswd()));
		user.setUpdNo(TssSession.getInfo().getUserNo());
		log.info("user: {}", user);

		// 비밀번호 수정
		loginService.updatePassword(user);

		return super.ok(message.getMessage("SUCC_0009"));
	}

}
