package com.dbnt.kcscbackend.file.service;

import com.dbnt.kcscbackend.admin.contents.popUp.model.FileVO;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.file.entity.TnAttachFile;
import com.dbnt.kcscbackend.file.repository.TnAttachFileRepository;
import com.dbnt.kcscbackend.util.NetworkUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Service
@RequiredArgsConstructor
public class FileService {

  private final TnAttachFileRepository tnAttachFileRepository;

  @Resource(name = "EgovFileMngUtil")
  private EgovFileMngUtil fileUtil;

  @Transactional
  public TnAttachFile selectTnAttachFile(TnAttachFile tnAttachFile) {
    if(tnAttachFile.getFileSeq()!=null){
      tnAttachFile = tnAttachFileRepository.findById(tnAttachFile.getFileSeq()).orElse(null);
    }else{
      tnAttachFile = Objects.requireNonNull(tnAttachFileRepository.findByFileGrpId(tnAttachFile.getFileGrpId()).orElse(null)).get(0);
    }
    int downCnt = tnAttachFile.getDownCnt()==null?0: tnAttachFile.getDownCnt();
    tnAttachFile.setDownCnt(downCnt+1);
    tnAttachFileRepository.save(tnAttachFile);
    return tnAttachFile;
  }






  public String addTnAttachFile(HttpServletRequest request, LoginVO user, MultipartFile[] files, String middlePath) throws Exception {
    return this.addTnAttachFile(request, user, files, middlePath, null);
  }

  public String addTnAttachFile(HttpServletRequest request, LoginVO user, MultipartFile file, String middlePath) throws Exception {
    MultipartFile[] files = new MultipartFile[1];
    return this.addTnAttachFile(request, user, files, middlePath);
  }

  /**
   * TN_ATTACH_FILE table에 insert 후, 파일 그룹 ID를 return 한다.
   * TN_ATTACH_FILE 참고.
   * @param request
   * @param user
   * @param files
   * @param middlePath 파일이 저장될 중간 경로다.
   *                   D:/kcscUploadFiles/XXXX/abc.jpg XXXX에 해당하는 경로다.
   *                   참고로 D:/kcscUploadFiles 값은 application-xxx.properties에 있는 Globals.fileStorePath를 통해 얻는다.
   * @return 파일 그룹 ID
   * @throws Exception
   */
  public String addTnAttachFile(HttpServletRequest request, LoginVO user, MultipartFile[] files, String middlePath, String fileGrpId) throws Exception {

    if( files == null ) {
      return fileGrpId;
    }
    String ipAddress = NetworkUtil.getClientIpAddress(request);


    if( fileGrpId == null || fileGrpId.trim().isEmpty()) {
      //String fileGrpId = UUID.randomUUID().toString();
      fileGrpId = tnAttachFileRepository.makeFileGrpId(user.getId());
    }


    for (MultipartFile file : files) {
      if( file != null && !file.isEmpty()) {

        Map<String, MultipartFile> filesMap = new HashMap<String, MultipartFile>();
        filesMap.put("file", file);

        List<FileVO> fileVoList =  fileUtil.parseFileInf(filesMap, "", 0, middlePath, null);

        int nCount = 1;
        // 업로드된 file을 tnAttachFile에 insert한다.
        for (Iterator<FileVO> iter = fileVoList.iterator(); iter.hasNext(); nCount++) {

          FileVO item         = iter.next();

          String fileNewName  = item.getStreFileNm() + "." + item.getFileExtsn();
          String filePath     = (item.getFileStreCours() + File.separator + item.getAtchFileId()).replaceAll("\\\\", "/") + fileNewName;
          tnAttachFileRepository.spAddTnAttachFile(
            fileGrpId,
            nCount,
            item.getOrignlFileNm(),
            fileNewName,
            filePath,
            Long.parseLong(item.getFileMg()),
            item.getFileExtsn(),
            ipAddress,
            user.getId(),
            null,
            null,
            null
          );

        }
      }
    }


    return fileGrpId;
  }


  /**
   * 특정 파일 하나를 삭제한다.
   * @param request
   * @param user
   * @param fileSeq
   * @return 삭제 성공 시, true. 실패 시, 예외
   * @throws Exception 예외
   */
  public boolean deleteTnAttachFile(HttpServletRequest request, LoginVO user, Long fileSeq) throws Exception {

    //파일을 삭제한다.

    TnAttachFile tnAttachFile = tnAttachFileRepository.findById(fileSeq.intValue()).orElse(null);

    if( tnAttachFile == null ) {
      throw new Exception("대상이 존재하지 않습니다.");
    }

    String fileFullPath = tnAttachFile.getFilePath();

    File file = new File(fileFullPath);
    file.delete();

    tnAttachFileRepository.deleteById(fileSeq.intValue());
    return true;
  }

  public  List<TnAttachFile> findByFileGrpId(String fileGrpId) throws Exception {
    return tnAttachFileRepository.findByFileGrpId(fileGrpId).orElse(null);
  }

}
