package com.mca.sec;

import java.io.IOException;
import java.time.LocalDateTime;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mca.cmmn.service.LogService;
import com.mca.cmmn.vo.LogActions;
import com.mca.cmmn.vo.LogVO;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.mca.sec.vo.LoginUserVO;
import com.mca.sec.UserUtil;

public class LoginSuccessHandler implements AuthenticationSuccessHandler{
	private String roleName;

  @Resource(name="logService")
  private LogService logService;



	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		LoginUserVO user = UserUtil.getMemberInfo();
		if(user == null){
      response.sendRedirect("/");
    }else{

      HttpSession session = request.getSession();
      session.setAttribute("userVO", user);

      LoginSuccessHandler loginSuccessHandler = new LoginSuccessHandler();
      authentication.getAuthorities().forEach(authority ->{
        loginSuccessHandler.roleName = authority.getAuthority();
      });

      LogVO logVO = new LogVO();
      logVO.setLog(user.getUserid(), LogActions.LOGIN.getValue(), null, LocalDateTime.now());
      logService.insertLog(logVO);

      switch (loginSuccessHandler.roleName) {
        case "ROLE_USER":
          response.sendRedirect("/map/request");
          return;
        case "ROLE_ADMIN":
          response.sendRedirect("/admin/dashBoard");
          return;
        case "ROLE_DISABLE":
          response.sendRedirect("/login?fail");
          return;
      }
    }
	}
	
}
