package egovframework.lab.ajax.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import egovframework.lab.ajax.service.LoginService;
import egovframework.lab.com.vo.Account;

import java.time.Duration;
import java.time.LocalDateTime;

@Controller
public class LoginController {

	@Autowired
	private LoginService loginService;

	@RequestMapping("/login.do")
	public void login(HttpServletRequest request, ModelMap model) {

		model.addAttribute("failCount", request.getSession()
					.getAttribute("UserAccountCount"));
	}
	
	@RequestMapping("/clean.do")
	public String clean(HttpServletRequest request, ModelMap model) {
		request.getSession().setAttribute("UserAccountCount", 0);
		request.getSession().setAttribute("UserAccountTime", null);
		return "redirect:/login.do";
	}

	@RequestMapping("/loginfail.do")
	public void loginfail(HttpServletRequest request, ModelMap model) {
		model.addAttribute("failCount", request.getSession()
					.getAttribute("UserAccountCount"));
	}
	
	@RequestMapping("/loginProcess.do")
	public String login(HttpServletRequest request, @RequestParam("id") String id,
	                    @RequestParam("password") String password, ModelMap model) {
		int loginFail = 0;
		LocalDateTime lastTime = LocalDateTime.now();
   
		if(request.getSession().getAttribute("UserAccountCount") == null) {
			loginFail = 0;
		} else {
			loginFail = Integer.parseInt(request.getSession()
					.getAttribute("UserAccountCount").toString()); 
		}		

		if(request.getSession().getAttribute("UserAccountTime") == null) {
			lastTime = LocalDateTime.now();
		} else { 
			lastTime = (LocalDateTime)request.getSession()
					.getAttribute("UserAccountTime");
		}

        // 시간 차 계산
        Duration duration = Duration.between(lastTime, LocalDateTime.now());

		System.out.println("------------" + loginFail);
		request.getSession().setAttribute("UserAccountCount", ++loginFail);
		request.getSession().setAttribute("UserAccountTime", LocalDateTime.now());
		model.addAttribute("failCount", loginFail);
		
		if(loginFail >= 5 && duration.toMinutes() <= 3) {
			return "redirect:/loginfail.do";
		} else {
			Account account;
			try {
				account = (Account) loginService.authenticate(id, password);
				request.getSession().setAttribute("UserAccountCount", 0);
				request.getSession().setAttribute("UserAccountTime", null);
				
			} catch (Exception e) {				
				return "login";
			}
			request.getSession().setAttribute("UserAccount", account);
			
			return "redirect:/employeelist.do";
		}

	}
}
