package incheon.ags.aip.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

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.com.cmm.EgovWebUtil;
import lombok.Getter;

@Component("aipFileUtil")
public class AipFileUtil extends EgovAbstractServiceImpl {

	@Value("${aip.file.path}")
	private String linuxPath;

	@Value("${aip.file.win.path}")
	private String winPath;

	@Getter
	public static class SavedFile {
		private String fileUuid;
		private String originalFileNm;
		private String dbFilePath;
		private long size;
		private String contentType;
	}

	/*
	 *	조서 저장: {base}/juckchul/year_YYYY/uuid.ext 
	 *	DB: /resources/ags/aip/juckchul/year_YYYY/uuid.ext
	*/
	public List<SavedFile> storeExtracFiles(List<MultipartFile> files, int year) throws Exception {
		String y = "year_" + year;

		String relDir = "juckchul/" + y + "/";
		String dbBaseDir = "/resources/ags/aip/juckchul/" + y + "/";

		return storeFiles(files, relDir, dbBaseDir);
	}

	/*
	 * 판독 저장
	 * 	rq: {base}/intpr_rqst/YYYY/MM/uuid.ext
	 * 	rs: {base}/intpr_rslt/YYYY/MM/uuid.ext
	 *	DB: /resources/ags/aip/{folder}/YYYY/MM/uuid.ext
	*/
	public List<SavedFile> storeIntprFiles(String partKey, List<MultipartFile> files, int year, int month) throws Exception {
		String y = String.valueOf(year);
		String m = String.format("%02d", month);

		String folder = "rs".equalsIgnoreCase(partKey) ? "intpr_rslt" : "intpr_rqst";

		String relDir = folder + "/" + y + "/" + m + "/";
		String dbBaseDir = "/resources/ags/aip/" + folder + "/" + y + "/" + m + "/";

		return storeFiles(files, relDir, dbBaseDir);
	}

	public boolean deleteByDbPath(String dbFilePath) throws Exception {
		if(dbFilePath == null || dbFilePath.trim().isEmpty()) return false;

		String p = dbFilePath.trim();

		String prefix = "/resources/ags/aip/";
		if(!p.startsWith(prefix)) return false;

		String rel = p.substring(prefix.length());

		String base = getOsPath();
		String physicalPath = base + rel;

		File f = new File(physicalPath);

		boolean ok = false;
		if(f.isFile()) {
			ok = f.delete();
		}

		return ok;
	}

	private List<SavedFile> storeFiles(List<MultipartFile> files, String relDir, String dbBaseDir) throws Exception {
		List<SavedFile> resultList = new ArrayList<>();
		if(files == null || files.isEmpty()) return resultList;

		String base = getOsPath();
		String dirPath = base + normalizeRelDir(relDir);

		File folder = new File(dirPath);
		if(!folder.isDirectory()) folder.mkdirs();

		for(int i = 0; i < files.size(); i++){
			MultipartFile mf = files.get(i);
			if(mf == null || mf.isEmpty()) continue;

			String original = (mf.getOriginalFilename() == null) ? "" : mf.getOriginalFilename();

			String ext = "";
			int dotIdx = original.lastIndexOf('.');
			if(dotIdx > -1) ext = original.substring(dotIdx).toLowerCase(Locale.ROOT);

			String uuid = UUID.randomUUID().toString().toLowerCase(Locale.ROOT);
			String saveFileNm = uuid + ext;

			String physicalPath = dirPath + saveFileNm;

			mf.transferTo(new File(EgovWebUtil.filePathBlackList(physicalPath)));

			SavedFile sf = new SavedFile();
			sf.fileUuid = uuid;
			sf.originalFileNm = original;
			sf.dbFilePath = dbBaseDir + saveFileNm;
			sf.size = mf.getSize();
			sf.contentType = mf.getContentType();

			resultList.add(sf);
		}

		return resultList;
	}
	
	public File toPhysicalFile(String dbPath) throws Exception {
		if(dbPath == null || dbPath.trim().isEmpty()) {
			return new File("");
		}

		String p = dbPath.trim();

		String prefix = "/resources/ags/aip/";
		int idx = p.indexOf(prefix);
		if(idx < 0) {
			return new File("");
		}
		p = p.substring(idx);

		String rel = p.substring(prefix.length());

		rel = rel.replace("/", File.separator);

		String base = getOsPath();
		String physicalPath = base + rel;

		return new File(EgovWebUtil.filePathBlackList(physicalPath));
	}

	private String normalizeRelDir(String relDir) {
		String s = (relDir == null) ? "" : relDir.trim();
		if(s.startsWith("/")) s = s.substring(1);
		if(!s.endsWith("/")) s = s + "/";
		return s;
	}

	private String getOsPath() {
		String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT);
		String base = osName.contains("win") ? winPath : linuxPath;

		if(base == null) base = "";
		base = base.trim();

		if(!base.endsWith("/") && !base.endsWith("\\")) base = base + "/";

		return base;
	}
}
