package com.style24.admin.biz.web;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.style24.admin.biz.service.TsaCommonService;
import com.style24.admin.support.controller.TsaBaseController;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.util.GagaFileUploadUtil;
import com.gagaframework.web.util.GagaFileUtil;
import com.gagaframework.web.util.GagaFtpUtil;
import com.gagaframework.web.util.GagaUploadedFileInfo;

/**
 * 공통 Controller
 *
 * @author renderer
 * @since 2020. 10. 22
 */
@Controller
@RequestMapping("/common")
@Slf4j
public class TsaCommonController extends TsaBaseController {


	@Autowired
	private Environment env;

	@Autowired
	private TsaCommonService commonService;


	@Value("${upload.default.target.path}")
	private String uploadTargetPath;

	/**
	 * Download a file
	 *
	 * @param request - HttpServletRequest
	 * @param downloadFile - 다운로드할 파일
	 * @return
	 * @throws IOException
	 * @author gagamel
	 * @since 2019. 12. 6
	 */
	@GetMapping("/file/download")
	@ResponseBody
	public ResponseEntity<InputStreamResource> downloadFile(HttpServletRequest request, @RequestParam("downloadFile") String downloadFile) throws IOException {
		String fileName = StringUtils.replace(downloadFile, "../", "");
		log.debug("fileName: {}", fileName);

		String downloadPath = env.getProperty("download.path");
		log.debug("downLoadPath :{}", downloadPath);

		String fileNameWithPath = GagaFileUtil.getConcatenationPath(downloadPath, fileName);
		log.debug("fileNameWithPath: {}", fileNameWithPath);

		return GagaFileUtil.writeFile(request, fileNameWithPath);
	}

	/**
	 * Upload a file
	 *
	 * @param subDir - 업로드 하위 디렉토리
	 * @param policy - 업로드 정책
	 * @param file - MultipartFile
	 * @return 업로드한 파일의 정보
	 * @throws IOException
	 * @author gagamel
	 * @since 2019. 12. 6
	 */
	@PostMapping("/file/upload")
	@ResponseBody
	public GagaUploadedFileInfo uploadFile(@RequestParam(value = "subDir") String subDir, @RequestParam(value = "policy", required = false) String policy, MultipartFile file) throws IOException {
		if (StringUtils.isEmpty(policy)) {
			policy = "default";
		}

		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload." + policy + ".target.path"), subDir);

		GagaFileUploadUtil fuUtil = new GagaFileUploadUtil(targetPath, Long.parseLong(env.getProperty("upload." + policy + ".max.size")), env.getProperty("upload." + policy + ".allow.extension"), env.getProperty("upload." + policy + ".view"));

		GagaUploadedFileInfo ufInfo = fuUtil.uploadFile(file);
		if (!"excel".equals(policy)) {
			// 운영서버에서만 FTP로 파일 업로드
			String profiles = env.getProperty("spring.profiles.active").toLowerCase();
			if ("run".equals(profiles) || "locp".equals(profiles)) {
				GagaFtpUtil ftpUtil = new GagaFtpUtil(env.getProperty("speedy.ftp.host"), env.getProperty("speedy.ftp.port"), env.getProperty("speedy.ftp.username"), env.getProperty("speedy.ftp.pwd"));

				File srcFile = new File(GagaFileUtil.getConcatenationPath(targetPath, ufInfo.getNewFileName()));
				ftpUtil.upload(srcFile, "/" + subDir);
				ftpUtil.close();
			}
		}
		return ufInfo;
	}

	/**
	 * Delete a file
	 *
	 * @param subDir - 업로드 하위 디렉토리
	 * @param fileNm - 파일명
	 * @return
	 * @throws IOException
	 * @author sasa004
	 * @since 2020. 04. 06
	 */
	@PostMapping("/file/delete")
	@ResponseBody
	public void deleteFile(@RequestParam(value = "subDir") String subDir, @RequestParam(value = "fileNm", required = false) String fileNm) throws IOException {
		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload.default.target.path"), subDir);

		GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, fileNm));

		// 운영서버이면 FTP 파일 삭제
		String profiles = env.getProperty("spring.profiles.active").toLowerCase();
		if ("run".equals(profiles) || "locp".equals(profiles)) {
			GagaFtpUtil ftpUtil = new GagaFtpUtil(env.getProperty("speedy.ftp.host"), env.getProperty("speedy.ftp.port"), env.getProperty("speedy.ftp.username"), env.getProperty("speedy.ftp.pwd"));
			log.debug("targetPath : " + targetPath);
			ftpUtil.delete("/" + subDir, fileNm);
			ftpUtil.close();
		}
	}

	/**
	 * Upload files
	 *
	 * @param subDir - 업로드 하위 디렉토리
	 * @param files - MultipartFile List
	 * @return 업로드한 파일의 정보
	 * @throws IOException
	 * @author gagamel
	 * @since 2019. 12. 6
	 */
	@PostMapping("/files/upload")
	@ResponseBody
	public Collection<GagaUploadedFileInfo> uploadFiles(@RequestParam(value = "subDir") String subDir, List<MultipartFile> files) throws IOException {
		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload.default.target.path"), subDir);
		GagaFileUploadUtil fuUtil = new GagaFileUploadUtil(targetPath);

		Collection<GagaUploadedFileInfo> ufList = fuUtil.uploadFiles(files);
		log.debug("ufList: {}", ufList);

		// 운영서버에서만 FTP로 파일 업로드
		String profiles = env.getProperty("spring.profiles.active").toLowerCase();
		if ("run".equals(profiles) || "locp".equals(profiles)) {
			if (ufList != null && !ufList.isEmpty()) {
				GagaFtpUtil ftpUtil = new GagaFtpUtil(env.getProperty("speedy.ftp.host"), env.getProperty("speedy.ftp.port"), env.getProperty("speedy.ftp.username"), env.getProperty("speedy.ftp.pwd"));

				for (GagaUploadedFileInfo ufInfo : ufList) {
					File srcFile = new File(GagaFileUtil.getConcatenationPath(targetPath, ufInfo.getNewFileName()));
					ftpUtil.upload(srcFile, "/" + subDir);
				}

				ftpUtil.close();
			}
		}

		return ufList;
	}

	/**
	 * 엑셀 업로드 팝업
	 *
	 * @param procJob - 업무명
	 * @param callBackFun - 콜백함수
	 * @return
	 * @author eskim
	 * @since 2019. 12. 6
	 */
	@GetMapping("/excel/upload/popup/form")
	public ModelAndView excelUploadPopupForm(@RequestParam(value = "procJob") String procJob, @RequestParam(value = "callBackFun", required = false) String callBackFun) {
		ModelAndView mav = new ModelAndView();

		GagaMap params = new GagaMap();
		params.setString("procJob", procJob);
		params.setString("callBackFun", callBackFun);

		mav.addObject("params", params);

		mav.setViewName("common/ExcelUploadPopupForm");

		return mav;
	}

	/**
	 * 샘플파일 시스템파일명 조회
	 * @param sampleFileId - 샘플파일ID
	 * @return
	 * @author gagamel
	 * @since 2020. 11. 3
	 */
	@GetMapping("/sample/file/{sampleFileId}")
	@ResponseBody
	public String getSampleFileSystemFilename(@PathVariable("sampleFileId") String sampleFileId) {
		return commonService.getSampleFileSystemFilename(sampleFileId);
	}
}
