package com.dbnt.kcgfilemanager;

import com.dbnt.kcgfilemanager.model.UserInfo;
import com.dbnt.kcgfilemanager.service.BoardCategoryService;
import com.dbnt.kcgfilemanager.service.CommonCodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.security.Principal;

@RestController
@RequiredArgsConstructor
public class BaseController {

  private final CommonCodeService commonCodeService;
  private final BoardCategoryService boardCategoryService;

  @GetMapping("/")
  public ModelAndView loginCheck(Principal principal, HttpSession session) {
    ModelAndView mav = null;
    if(principal == null){
      mav = new ModelAndView("redirect:/user/login");
    }else{
      session.setAttribute("positionList", commonCodeService.selectCommonCodeValue("POSITION"));
      session.setAttribute("departmentList", commonCodeService.selectCommonCodeValue("DEPARTMENT"));
      session.setAttribute("categoryList", boardCategoryService.selectBoardCategoryAll(null, 1));
      if(((UserInfo)((UsernamePasswordAuthenticationToken) principal).getPrincipal()).getUserRole().indexOf("ADMIN")>0){
        mav = new ModelAndView("redirect:/admin/main");
      }else{
        mav = new ModelAndView("redirect:/user/main");
      }
    }
    return mav;
  }

  @GetMapping("/user/main")
  public ModelAndView main() {
    ModelAndView mav = new ModelAndView("main");
    return mav;
  }

  @GetMapping("/refreshSession")
  public void getSession(HttpSession session){
    session.setAttribute("positionList", commonCodeService.selectCommonCodeValue("POSITION"));
    session.setAttribute("departmentList", commonCodeService.selectCommonCodeValue("DEPARTMENT"));
    session.setAttribute("categoryList", boardCategoryService.selectBoardCategoryAll(null, 1));
  }
}
