package com.dbnt.kcgfilemanager.controller;

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.core.annotation.AuthenticationPrincipal;
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;

@RestController
@RequiredArgsConstructor
public class BaseController {

  private final CommonCodeService commonCodeService;
  private final BoardCategoryService boardCategoryService;

  @GetMapping("/")
  public ModelAndView loginCheck(@AuthenticationPrincipal UserInfo loginUser, HttpSession session) {
    ModelAndView mav = null;
    if(loginUser == 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(loginUser.getUserRole().indexOf("ADMIN")>0){
        mav = new ModelAndView("redirect:/admin/main");
      }else{
        mav = new ModelAndView("redirect:/board/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));
  }

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

  @GetMapping("/login-error")
  public ModelAndView loginError() {
    ModelAndView mav = new ModelAndView("/login");
    mav.addObject("loginError", true);
    return mav;
  }

  @GetMapping("/denied")
  public ModelAndView doDenied() {
    ModelAndView mav = new ModelAndView("login/denied");
    return mav;
  }
}
