package com.dbnt.kcgfilemanager.controller;

import com.dbnt.kcgfilemanager.model.Board;
import com.dbnt.kcgfilemanager.model.UserInfo;
import com.dbnt.kcgfilemanager.service.BoardService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import java.security.Principal;

@RestController
@RequiredArgsConstructor
@RequestMapping("/board")
public class BoardController {

  private final BoardService boardService;

  @GetMapping("/contentWrite")
  public ModelAndView contentWrite(Principal principal) {
    ModelAndView mav = new ModelAndView("board/contentWrite");
    UserInfo loginUser = ((UserInfo)((UsernamePasswordAuthenticationToken) principal).getPrincipal());
    mav.addObject("userId", loginUser.getUserId());
    mav.addObject("userName", loginUser.getName());
    return mav;
  }

  @PostMapping("/saveContent")
  public Integer saveContent(Board content, MultipartHttpServletRequest request){
    content.setFileList(request.getMultiFileMap().get("uploadFiles"));
    return boardService.saveContent(content);
  }

  @GetMapping("/contentList")
  public ModelAndView contentList(Board board){
    ModelAndView mav = new ModelAndView("board/contentList");
    mav.addObject("pageTitle", boardService.getPageTitle(board.getCategorySeq()));
    board.setQueryInfo();
    mav.addObject("contentList", boardService.selectContentList(board));
    board.setContentCnt(boardService.selectContentListCnt(board));
    board.setPaginationInfo();
    mav.addObject("searchParams", board);
    return mav;
  }
}
