package com.dbnt.kcscbackend.file;

import com.dbnt.kcscbackend.admin.logs.service.AdminLogsService;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.config.util.ClientUtils;
import com.dbnt.kcscbackend.file.entity.TnAttachFile;
import com.dbnt.kcscbackend.file.service.FileService;
import com.dbnt.kcscbackend.standardCode.service.StandardCodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequiredArgsConstructor
@RequestMapping("/file")
public class FileController {

  private final FileService fileService;
  private final AdminLogsService adminLogsService;

  @RequestMapping(method = RequestMethod.GET, value = "/download")
  public void download(HttpServletRequest request, HttpServletResponse response, TnAttachFile tnAttachFile) throws Exception{
    tnAttachFile = fileService.selectTnAttachFile(tnAttachFile);
    fileDownload(request, response, tnAttachFile);
  }

  @RequestMapping(method = RequestMethod.GET, value = "/standardCode-download")
  public void standardCodeDownload(HttpServletRequest request, HttpServletResponse response, TnAttachFile tnAttachFile, String userId) throws Exception{
    tnAttachFile = fileService.selectTnAttachFile(tnAttachFile);
    adminLogsService.insertFileLog(tnAttachFile, userId, ClientUtils.getRemoteIP(request));
    fileDownload(request, response, tnAttachFile);
  }

  private void fileDownload(HttpServletRequest request, HttpServletResponse response, TnAttachFile tnAttachFile){
    if(tnAttachFile != null){
      BufferedInputStream in;
      BufferedOutputStream out;
      try {
        File file = new File(tnAttachFile.getFilePath());

        ClientUtils.setDisposition(tnAttachFile.getFileOldName(), request, response);
        in = new BufferedInputStream(new FileInputStream(file));
        out = new BufferedOutputStream(response.getOutputStream());
        FileCopyUtils.copy(in, out);
        out.flush();
        if(out!=null) out.close();
        if(in!=null )in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
