package com.dbnt.kcgfilemanager.service;

import com.dbnt.kcgfilemanager.mapper.BoardMapper;
import com.dbnt.kcgfilemanager.model.*;
import com.dbnt.kcgfilemanager.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class BoardService {

  private final BoardRepository boardRepository;
  private final BoardLogRepository boardLogRepository;
  private final HashTagRepository hashTagRepository;
  private final HashTagLinkRepository hashTagLinkRepository;
  private final FileInfoRepository fileInfoRepository;
  private final BoardCategoryRepository boardCategoryRepository;
  private final BoardMapper boardMapper;

  @Transactional
  public Integer saveContent(Board content){
    Integer contentSeq = boardRepository.save(content).getContentSeq();
    saveBoardLog(contentSeq, "I", null, content.getCreateId());
    saveHashTagLink(contentSeq, content.getHashTagStr());
    saveUploadFiles(contentSeq, content.getCategorySeq(), content.getFileList());
    return contentSeq;
  }

  private void saveBoardLog(Integer contentSeq, String status, String description, String createId){
    BoardLog lastLog = boardLogRepository.findTopByContentSeqOrderByLogSeqDesc(contentSeq).orElse(null);
    BoardLog log = new BoardLog();
    log.setContentSeq(contentSeq);
    log.setLogSeq(lastLog == null?1:(lastLog.getLogSeq()+1));
    log.setLogStatus(status);
    log.setDescription(description);
    log.setCreateId(createId);
    boardLogRepository.save(log);
  }

  private HashTag saveHashTag(String tagName){
    HashTag tag = new HashTag();
    tag.setTagName(tagName);
    return hashTagRepository.save(tag);
  }

  private void saveHashTagLink(Integer contentSeq, String hashTagStr){
    String[] hashTagAry = hashTagStr.trim().replaceAll(",", "").split("#");
    for(String tagName : hashTagAry){
      if(!tagName.equals("")){
        HashTag tag = hashTagRepository.findByTagName(tagName).orElse(null);
        if(tag==null){
          tag = saveHashTag(tagName);
        }
        HashTagLink link = new HashTagLink();
        link.setContentSeq(contentSeq);
        link.setTagSeq(tag.getTagSeq());
        hashTagLinkRepository.save(link);
      }
    }
  }
  private void saveUploadFiles(Integer contentSeq, Integer categorySeq, List<MultipartFile> files){
    FileInfo lastFileInfo = fileInfoRepository.findTopByContentSeqOrderByFileSeqDesc(contentSeq).orElse(null);
    int fileSeq = lastFileInfo==null?1:(lastFileInfo.getFileSeq()+1);
    for(MultipartFile file : files){
      System.out.println(file.getName());
      String saveName = UUID.randomUUID().toString();
      String path = makeFilePath(categorySeq);

      File saveFile = new File(path+"\\"+saveName);
      if(file.getSize()!=0){ // 저장될 파일 확인
        if(!saveFile.exists()){ // 저장될 경로 확인
          if(saveFile.getParentFile().mkdirs()){
            try{
              saveFile.createNewFile();
            }catch (IOException e){
              e.printStackTrace();
            }
          }
        }
        try {
          file.transferTo(saveFile);
        }catch (IllegalStateException | IOException e){
          e.printStackTrace();
        }
      }

      String[] originalFilename = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
      FileInfo fileInfo = new FileInfo();
      fileInfo.setContentSeq(contentSeq);
      fileInfo.setFileSeq(fileSeq++);
      fileInfo.setOriginalName(originalFilename[0]);
      fileInfo.setExtention(originalFilename[1]);
      fileInfo.setConversionName(saveName);
      fileInfo.setSavePath(path);
      fileInfoRepository.save(fileInfo);
    }
  }

  public String getPageTitle(Integer categorySeq) {
    BoardCategory category = boardCategoryRepository.findById(categorySeq).orElse(null);
    if(category.getParentSeq()==null){
      return category.getCategoryName();
    }
    return getPageTitle(category.getParentSeq())+" > "+category.getCategoryName();
  }

  public String makeFilePath(Integer categorySeq){
    BoardCategory category = boardCategoryRepository.findById(categorySeq).orElse(null);
    if(category.getParentSeq()==null){
      return "D:\\kcgFileManager\\"+category.getCategoryName();
    }
    return makeFilePath(category.getParentSeq())+"\\"+category.getCategoryName();
  }

  public List<Board> selectContentList(Board board) {
    return boardMapper.selectContentList(board);
  }
  public Integer selectContentListCnt(Board board) {
    return boardMapper.selectContentListCnt(board);
  }
}
