package com.style24.scm.biz.web;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.style24.core.support.message.TscMessageByLocale;
import com.style24.scm.biz.service.TssLoginService;
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;

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

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TssLoginService loginService;

	/**
	 * 첫 페이지
	 * 		로그인 하고
	 * 			2factor인증까지 되었으면 대쉬보드 화면으로 이동하고
	 * 			아니면 2factor인증 화면으로
	 * 		아니면 로그인 페이지로
	 * @param error - 로그인 오류 정보
	 * @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.setViewName("dashboard");
			} else {
				// 2factor인증번호 발송
				loginService.sendTwoFactorCertNo();

				// 2factor인증 페이지로
				mav.setViewName("signin2");
			}
			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"));
	}

}
