package com.dbnt.faisp.main.ivsgtMgt.boardInvestigation.service;


import com.dbnt.faisp.config.BaseService;
import com.dbnt.faisp.config.FileInfo;
import com.dbnt.faisp.main.hashTag.service.HashTagService;
import com.dbnt.faisp.main.ivsgtMgt.boardInvestigation.mapper.BoardInvestigationMapper;
import com.dbnt.faisp.main.ivsgtMgt.boardInvestigation.model.*;
import com.dbnt.faisp.main.ivsgtMgt.boardInvestigation.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.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class BoardInvestigationService extends BaseService {
  private final HashTagService hashTagService;
  private final BoardInvestigationRepository boardInvestigationRepository;
  private final IvsgtFileRepository ivsgtFileRepository;
  private final ArrestTypeRepository arrestTypeRepository;
  private final RelatedReportsRepository relatedReportsRepository;
  private final HashTagLinkIvsgtRepository hashTagLinkIvsgtRepository;
  private final BoardInvestigationMapper boardInvestigationMapper;

  public List<BoardInvestigation> selectBoardInvestigationList(BoardInvestigation boardInvestigation) {
    return boardInvestigationMapper.selectBoardInvestigationList(boardInvestigation);
  }

  public Integer selectBoardInvestigationListCnt(BoardInvestigation boardInvestigation) {
    return boardInvestigationMapper.selectBoardInvestigationListCnt(boardInvestigation);
  }

  public BoardInvestigation selectBoardInvestigation(Integer ivsgtKey) {
    BoardInvestigation savedBoardInvestigation = boardInvestigationRepository.findById(ivsgtKey).orElse(null);
    if (savedBoardInvestigation != null) {
      savedBoardInvestigation.setFileList(ivsgtFileRepository.findByIvsgtKey(ivsgtKey));
      savedBoardInvestigation.setHashTags(boardInvestigationMapper.selectHashTags(ivsgtKey));
      savedBoardInvestigation.setArrestType(boardInvestigationMapper.selectArrestType(ivsgtKey));
      savedBoardInvestigation.setRelatedReportsList(boardInvestigationMapper.selectRelatedReportsList(ivsgtKey));
    }
    return savedBoardInvestigation;
  }

  @Transactional
  public Integer saveBoardInvestigation(BoardInvestigation boardInvestigation, ArrestType arrestType, RelatedReports relatedReports, List<Integer> deleteFileSeq) {
    Integer ivsgtKey = boardInvestigationRepository.save(boardInvestigation).getIvsgtKey();
    String[] hashTagAry = boardInvestigation.getHashTags().split(" ");
    if(hashTagAry.length>0){
      saveHashTagLink(ivsgtKey, hashTagAry);
    }
    arrestType.setIvsgtKey(ivsgtKey);
    arrestTypeRepository.save(arrestType);

    if (relatedReports.getDeleteKeyList() != null) {
      relatedReportsRepository.deleteAllByIdInQuery(relatedReports.getDeleteKeyList());
    }

    if (relatedReports.getChildIvsgtKeyList() != null) {
      List<RelatedReports> relatedReportsList = new ArrayList<>();
      for (int i = 0; i < relatedReports.getChildIvsgtKeyList().size(); i++) {
        RelatedReports relatedReportsTemp = new RelatedReports();
        if (relatedReports.getRelatedReportsKeyList().get(i) > 0) {
          relatedReportsTemp.setRelatedReportsKey(relatedReports.getRelatedReportsKeyList().get(i));
        }
        relatedReportsTemp.setChildIvsgtKey(relatedReports.getChildIvsgtKeyList().get(i));
        relatedReportsTemp.setParentIvsgtKey(ivsgtKey);
        relatedReportsList.add(relatedReportsTemp);
      }
      relatedReportsRepository.saveAll(relatedReportsList);
    }

    if(deleteFileSeq != null && deleteFileSeq.size()>0){
      deletIvsgtFile(ivsgtKey, deleteFileSeq);
    }
    if(boardInvestigation.getMultipartFileList()!=null){
      saveUploadFiles(ivsgtKey, boardInvestigation.getMultipartFileList());
    }
    return ivsgtKey;
  }

  private void saveUploadFiles(Integer ivsgtKey, List<MultipartFile> multipartFileList){
    IvsgtFile lastFileInfo = ivsgtFileRepository.findTopByIvsgtKeyOrderByFileSeqDesc(ivsgtKey).orElse(null);
    int fileSeq = lastFileInfo==null?1:(lastFileInfo.getFileSeq()+1);
    for(MultipartFile file : multipartFileList){
      String saveName = UUID.randomUUID().toString();
      String path = locationPath+ File.separator+"ivsgt"+File.separator;
      saveFile(file, new File(path+File.separator+saveName));

      String originalFilename = file.getOriginalFilename();
      int extnIdx = originalFilename.lastIndexOf(".");
      IvsgtFile fileInfo = new IvsgtFile();
      fileInfo.setIvsgtKey(ivsgtKey);
      fileInfo.setFileSeq(fileSeq++);
      fileInfo.setOrigNm(originalFilename.substring(0, extnIdx));
      fileInfo.setFileExtn(originalFilename.substring(extnIdx+1));
      fileInfo.setConvNm(saveName);
      fileInfo.setFileSize(calculationSize(file.getSize()));
      fileInfo.setSavePath(path);
      ivsgtFileRepository.save(fileInfo);
    }
  }

  private void deletIvsgtFile(Integer ivsgtKey, List<Integer> deleteFileSeq) {
    List<IvsgtFile> ivsgtFileList = ivsgtFileRepository.findByIvsgtKey(ivsgtKey);
    for(IvsgtFile file: ivsgtFileList){
      if(deleteFileSeq.contains(file.getFileSeq())){
        deleteStoredFile(new File(file.getSavePath(), file.getConvNm()));
        ivsgtFileRepository.delete(file);
      }
    }
  }

  private void saveHashTagLink(Integer ivsgtKey, String[] hashTagAry){
    hashTagLinkIvsgtRepository.deleteByIvsgtKey(ivsgtKey);
    for(String tagNm : hashTagAry){
      HashTagLinkIvsgt hashTagLinkIvsgt = new HashTagLinkIvsgt();
      hashTagLinkIvsgt.setIvsgtKey(ivsgtKey);
      hashTagLinkIvsgt.setTagKey(hashTagService.selectTagKey(tagNm));
      hashTagLinkIvsgtRepository.save(hashTagLinkIvsgt);
    }
  }

  public FileInfo selectIvsgtFile(Integer parentKey, Integer fileSeq) {
    return ivsgtFileRepository.findById(new IvsgtFile.IvsgtFileId(parentKey, fileSeq)).orElse(null);
  }
}
