package incheon.ags.por.util;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.compress.utils.FileNameUtils;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import incheon.ags.por.mapper.PorFileUtilsMapper;
import incheon.ags.por.vo.PorFileVO;
import incheon.com.cmm.EgovWebUtil;
import incheon.com.cmm.service.FileVO;
import lombok.RequiredArgsConstructor;

/**
 * 게시물 파일 관리
 */
@Component("porFileUtils")
@RequiredArgsConstructor
public class PorFileUtils extends EgovAbstractServiceImpl {
	
	@Value("${por.board.file.window.path}")
	private String winPath;
	@Value("${por.board.file.linux.path}")
	private String linuxPath;

	private final PorFileUtilsMapper porFileUtilsMapper;

	/**
	 * 단일 파일 저장 (Summernote 등 에디터 이미지 업로드용)
	 * @param file 업로드 파일
	 * @return 저장된 파일 정보 (unqKey, atchFileSn 등)
	 */
	public PorFileVO storeFile(MultipartFile file) throws Exception {
		if (file == null || file.isEmpty()) {
			return null;
		}
		List<PorFileVO> list = storeFiles(java.util.Collections.singletonList(file));
		return (list == null || list.isEmpty()) ? null : list.get(0);
	}

    public List<PorFileVO> storeFiles(List<MultipartFile> files) throws Exception {
    	
    	List<PorFileVO> resultList = new ArrayList<PorFileVO>();
    	
    	LocalDate now = LocalDate.now();
    	DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    	String formatedNow = now.format(formatter);
    	
    	AtomicInteger atchFileSn = new AtomicInteger(0);
    	
		files.forEach(file -> {
			try {
				// 개발서버 리눅스같은데...한번 확인해보기
				/*
				 * String osName = System.getProperty("os.name").toLowerCase();
				 * if(!osName.contains("win") && !PATH.contains("idc")) { PATH =
				 * "/idc01/mw/idsp/resource/sgp/por/bbs/"; }
				 */
				
				PorFileVO fileVO = new PorFileVO();
				
				fileVO.setAtchFileSn(atchFileSn.getAndIncrement());
				
				String newName = UUID.randomUUID().toString();
				String basePath = getOsPath().replaceAll("[/\\\\]+$", "") + File.separator;
				Path dirPath = Paths.get(basePath, formatedNow, newName);
				Files.createDirectories(dirPath);
				String atchmnflStrgPath = dirPath.toString() + File.separator;
				fileVO.setAtchFilePathNm(atchmnflStrgPath);
				
				Path targetFile = dirPath.resolve(newName);
				file.transferTo(new File(EgovWebUtil.filePathBlackList(targetFile.toString())));
		    	
				fileVO.setSrvrAtchFileNm(newName);
				
				fileVO.setOrgnlAtchFileNm(file.getOriginalFilename());
				
				fileVO.setAtchFileExtnNm(FileNameUtils.getExtension(fileVO.getOrgnlAtchFileNm()));
				
				fileVO.setAtchmnflCpct(file.getSize());
			
				porFileUtilsMapper.insertFileInfo(fileVO);
				resultList.add(fileVO);
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
		
    	return resultList;
    	
    }
    
    
    public int deleteFiles(PorFileVO file) throws Exception {
    	
    	String filePath = file.getAtchFilePathNm() + file.getSrvrAtchFileNm();
    	
    	File f = new File(filePath);
    	
    	int result = 0;
    	
    	if(f.isFile()) {
    		if(f.delete()) {
				File folder = new File(file.getAtchFilePathNm());
				if(folder.isDirectory()) {
					folder.delete();
				}
				result = porFileUtilsMapper.deleteFileInfo(file);
    		}
    	}
    	
    	return result;
    }
    
    private String getOsPath() {
    	String osName = System.getProperty("os.name").toLowerCase();
    	if (osName.contains("win")) {
    		return winPath;
    	} else {
    		return linuxPath;
    	}
    }

    /**
     * 에디터 이미지 저장 (확장명 포함, 단순 구조)
     * @param file 업로드 파일
     * @return 저장된 파일 정보
     */
    public PorFileVO storeEditorImage(MultipartFile file) throws Exception {
    	if (file == null || file.isEmpty()) {
    		return null;
    	}

    	LocalDate now = LocalDate.now();
    	DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    	String formatedNow = now.format(formatter);

    	PorFileVO fileVO = new PorFileVO();
    	fileVO.setAtchFileSn(0);

    	// 원본 파일명에서 확장명 추출
    	String originalFilename = file.getOriginalFilename();
    	String extension = FileNameUtils.getExtension(originalFilename);
    	String newName = UUID.randomUUID().toString() + "." + extension;

    	// 날짜 폴더만 생성 (UUID 폴더 없음) - 게시판 파일 경로 아래 poreditor 사용
    	String basePath = getOsPath().replaceAll("[/\\\\]+$", "") + File.separator + "poreditor" + File.separator;
    	Path dirPath = Paths.get(basePath, formatedNow);
    	Files.createDirectories(dirPath);

    	String atchmnflStrgPath = dirPath.toString() + File.separator;
    	fileVO.setAtchFilePathNm(atchmnflStrgPath);

    	// 파일 저장 (확장명 포함)
    	Path targetFile = dirPath.resolve(newName);
    	file.transferTo(new File(EgovWebUtil.filePathBlackList(targetFile.toString())));

    	fileVO.setSrvrAtchFileNm(newName);
    	fileVO.setOrgnlAtchFileNm(originalFilename);
    	fileVO.setAtchFileExtnNm(extension);
    	fileVO.setAtchmnflCpct(file.getSize());

    	porFileUtilsMapper.insertFileInfo(fileVO);

    	return fileVO;
    }

    /**
     * 에디터 이미지 삭제 (폴더 삭제 없음)
     * @param file 파일 정보
     * @return 삭제 결과
     */
    public int deleteEditorImage(PorFileVO file) throws Exception {
    	String filePath = file.getAtchFilePathNm() + file.getSrvrAtchFileNm();
    	File f = new File(filePath);

    	int result = 0;
    	if (f.isFile() && f.delete()) {
    		result = porFileUtilsMapper.deleteFileInfo(file);
    	}

    	return result;
    }

} 