package com.madeu.util;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import com.madeu.constants.Constants;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class FileStoreUtil {
	
	private static String path;
	
	@Value("${file.upload-path}")
	public void setPath(String url) {
		path = url;
	}
	
	public static HashMap<String, Object> checkFileImage(MultipartFile file, boolean require) throws Exception{
		return checkFileImage(file, require, 10);
	}
	
	public static HashMap<String, Object> checkAppFileImage(MultipartFile file, boolean require) throws Exception{
		return checkAppFileImage(file, require, 10);
	}

	public static HashMap<String, Object> checkAppFileVideo(MultipartFile file, boolean require) throws Exception{
		return checkAppFileVideo(file, require, 50);
	}

	public static HashMap<String, Object> checkAppFile(MultipartFile file, boolean require) throws Exception{
		return checkAppFile(file, require, 50);
	}

	public static HashMap<String, Object> checkAppFile2(MultipartFile file, boolean require) throws Exception{
		return checkAppFile2(file, require, 100);
	}

	public static HashMap<String, Object> checkFileImage(MultipartFile file, boolean require, int maxSize) throws Exception{

		long MAX_FILE_SIZE = maxSize*1024*1024;    //1*1024*1024; // 1M파일 용량사이즈 
		long MIN_FILE_SIZE = 0;
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		log.debug("file       :"+file);

		map.put("check", true);
		if(file == null||file.getSize()==0){
			if(require){
				map.put("check", false);
				map.put("msgDesc", "파일이 누락되었습니다.");
			}
		}else{
			String filename = file.getOriginalFilename();
			String ext = filename.substring(filename.lastIndexOf(".")+1,filename.length()).toLowerCase();
			log.debug("ext        : "+ ext);
			
			/*
			if(("image/jpeg").equals(ext)||("image/png").equals(ext)){
				
			}else{
				map.put("check", false);
				map.put("msgDesc", "이미지 파일은 jpg 또는 png 파일만 등록 가능합니다.");
			}
			*/
			if(("jpeg").equals(ext)||("jpg").equals(ext)||("png").equals(ext)){
				
			}else{
				map.put("check", false);
				map.put("msgDesc", "이미지 파일은 jpg 또는 png 파일만 등록 가능합니다.");
			}
			
			log.debug("file.getSize()   :" + file.getSize());
			if( MAX_FILE_SIZE>=file.getSize() && MIN_FILE_SIZE<file.getSize()){
				
			}else{
				map.put("check", false);
				map.put("msgDesc", "이미지 파일 용량이 "+maxSize+"M byte 이상은 올릴 수 없습니다.");
			}
			map.put("ext", ext);
		}
		return map;
	}
	
	public static HashMap<String, Object> checkAppFileImage(MultipartFile file, boolean require, int maxSize) throws Exception{

		long MAX_FILE_SIZE = maxSize*1024*1024;    //1*1024*1024; // 1M파일 용량사이즈 
		long MIN_FILE_SIZE = 0;
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		log.debug("file       :"+file);

		map.put("check", true);
		if(file == null||file.getSize()==0){
			if(require){
				map.put("check", false);
				map.put("msgDesc", "파일이 누락되었습니다.");
			}
		}else{
			String filename = file.getOriginalFilename();
			String ext = filename.substring(filename.lastIndexOf(".")+1,filename.length()).toLowerCase();
			log.debug("ext        : "+ ext);
			
			log.debug("file.getSize()   :" + file.getSize());
			if( MAX_FILE_SIZE>=file.getSize() && MIN_FILE_SIZE<file.getSize()){
				
			}else{
				map.put("check", false);
				map.put("msgDesc", "이미지 파일 용량이 "+maxSize+"M byte 이상은 올릴 수 없습니다.");
			}
			map.put("ext", ext);
		}
		return map;
	}

	public static HashMap<String, Object> checkAppFileVideo(MultipartFile file, boolean require, int maxSize) throws Exception{

		long MAX_FILE_SIZE = maxSize*1024*1024;    //5*1024*1024; // 5M파일 용량사이즈
		long MIN_FILE_SIZE = 0;

		HashMap<String, Object> map = new HashMap<String, Object>();
		log.debug("file       :"+file);

		map.put("check", true);
		if(file == null||file.getSize()==0){
			if(require){
				map.put("check", false);
				map.put("msgDesc", "파일이 누락되었습니다.");
			}
		}else{
			String filename = file.getOriginalFilename();
			String ext = filename.substring(filename.lastIndexOf(".")+1,filename.length()).toLowerCase();
			log.debug("ext        : "+ ext);

			log.debug("file.getSize()   :" + file.getSize());
			if( MAX_FILE_SIZE>=file.getSize() && MIN_FILE_SIZE<file.getSize()){

			}else{
				map.put("check", false);
				map.put("msgDesc", "동영상 파일 용량 "+maxSize+"M byte 이상은 올릴 수 없습니다.");
			}
			map.put("ext", ext);
		}
		return map;
	}

	public static HashMap<String, Object> checkAppFile(MultipartFile file, boolean require, int maxSize) throws Exception{

		long MAX_FILE_SIZE = maxSize*1024*1024;    //5*1024*1024; // 5M파일 용량사이즈
		long MIN_FILE_SIZE = 0;

		HashMap<String, Object> map = new HashMap<String, Object>();
		log.debug("file             :"+file);

		map.put("check", true);
		if(file == null||file.getSize()==0){
			if(require){
				map.put("check", false);
				map.put("msgDesc", "파일이 누락되었습니다.");
			}
		}else{
			String filename = file.getOriginalFilename();
			String ext = filename.substring(filename.lastIndexOf(".")+1,filename.length()).toLowerCase();
			log.debug("ext              :"+ ext);

			// 가능 확장자
			String[] extArray = {"gif","png","jpg","jpeg","doc","docx","xls","xlsx","hwp","hwpx","pdf","ppt","pptx"};

			boolean isPermissionFileExt = false;
			for( int i = 0; i < extArray.length; i++ ) {
				if( extArray[i].equals(ext) ) {
					isPermissionFileExt = true;
					break;
				}
			}

			if(isPermissionFileExt==false){
				map.put("check", false);
				map.put("msgDesc", "등록 가능한 파일이 아닙니다.");
			}

			log.debug("file.getSize()   :" + file.getSize());
			if( MAX_FILE_SIZE>=file.getSize() && MIN_FILE_SIZE<file.getSize()){

			}else{
				map.put("check", false);
				map.put("msgDesc", "양식 파일 용량이 "+maxSize+"M byte 이상은 올릴 수 없습니다.");
			}
			map.put("ext", ext);
		}
		return map;
	}

	public static HashMap<String, Object> checkAppFile2(MultipartFile file, boolean require, int maxSize) throws Exception{

		long MAX_FILE_SIZE = maxSize*1024*1024;    //5*1024*1024; // 5M파일 용량사이즈
		long MIN_FILE_SIZE = 0;

		HashMap<String, Object> map = new HashMap<String, Object>();
		log.debug("file       :"+file);

		map.put("check", true);
		if(file == null||file.getSize()==0){
			if(require){
				map.put("check", false);
				map.put("msgDesc", "파일이 누락되었습니다.");
			}
		}else{
			String filename = file.getOriginalFilename();
			String ext = filename.substring(filename.lastIndexOf(".")+1,filename.length()).toLowerCase();
			log.debug("ext        : "+ ext);

			// 가능 확장자
			String[] extArray = {"gif","png","jpg","jpeg","pdf","svg"};

			boolean isPermissionFileExt = false;
			for( int i = 0; i < extArray.length; i++ ) {
				if( extArray[i].equals(ext) ) {
					isPermissionFileExt = true;
					break;
				}
			}

			if(isPermissionFileExt==false){
				map.put("check", false);
				map.put("msgDesc", "등록 가능한 파일이 아닙니다.");
			}

			log.debug("file.getSize()   :" + file.getSize());
			if( MAX_FILE_SIZE>=file.getSize() && MIN_FILE_SIZE<file.getSize()){

			}else{
				map.put("check", false);
				map.put("msgDesc", "양식 파일 용량이 "+maxSize+"M byte 이상은 올릴 수 없습니다.");
			}
			map.put("ext", ext);
		}
		return map;
	}

	public static HashMap<String, Object> checkFileExcel(MultipartFile file, boolean require) throws Exception{
		return checkFileExcel(file, require, 5);
	}
	
	public static HashMap<String, Object> checkFileExcel(MultipartFile file, boolean require, int maxSize) throws Exception{

		long MAX_FILE_SIZE = maxSize*1024*1024;    //5*1024*1024; // 5M파일 용량사이즈 
		long MIN_FILE_SIZE = 0;
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		log.debug("file       :"+file);

		map.put("check", true);
		if(file == null||file.getSize()==0){
			if(require){
				map.put("check", false);
				map.put("msgDesc", "파일이 누락되었습니다.");
			}
		}else{
			String filename = file.getOriginalFilename();
			String ext = filename.substring(filename.lastIndexOf(".")+1,filename.length()).toLowerCase();
			log.debug("ext        : "+ ext);
			
			/*
			if(("application/vnd.ms-excel").equals(ext)){
				
			}else{
				map.put("check", false);
				map.put("msgDesc", "엑셀 파일은 xls 파일만 등록 가능합니다.");
			}
			*/
			if(("xls").equals(ext)||("xlsx").equals(ext)){
				
			}else{
				map.put("check", false);
				map.put("msgDesc", "이미지 파일은 xls 또는 xlsx 파일만 등록 가능합니다.");
			}
			
			log.debug("file.getSize()   :" + file.getSize());
			if( MAX_FILE_SIZE>=file.getSize() && MIN_FILE_SIZE<file.getSize()){
				
			}else{
				map.put("check", false);
				map.put("msgDesc", "엑셀 파일 용량이 "+maxSize+"M byte 이상은 올릴 수 없습니다.");
			}
			map.put("ext", ext);
		}
		return map;
	}
	
	public static String saveFile(String folder, MultipartFile file) throws Exception{
		String returnPath = "";
		
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMdd");
	
		String pathTemp = folder.concat("/").concat(formatter.format(calendar.getTime()).concat("/"));
		String newPath = path.concat(pathTemp);
		
		File dir = new File(newPath);
		if(!dir.exists()){
			dir.mkdirs();
		}

		String originalFilename = file.getOriginalFilename();
		String ext = originalFilename.substring(originalFilename.lastIndexOf(".")+1,originalFilename.length());
		log.debug("ext        : "+ ext);
		
		String fileName =  System.currentTimeMillis()+"."+ext;
		
		log.debug("newPath       :"+newPath);
		log.debug("fileName      :"+fileName);
		
		try{
			File saveFile = new File(newPath.concat(fileName));
			if(!saveFile.exists())
				saveFile.createNewFile();
			FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(saveFile));
		}catch (IOException e) {
			throw new Exception(e.getMessage());
		}
		
		returnPath = pathTemp.concat(fileName);
		return returnPath;
	}
	
	public static String saveFile(String folder, MultipartFile file, String ext) throws Exception{
		String returnPath = "";
		
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMdd");
	
		String pathTemp = folder.concat("/").concat(formatter.format(calendar.getTime()).concat("/"));
		String newPath = path.concat(pathTemp);
		
		File dir = new File(newPath);
		if(!dir.exists()){
			dir.mkdirs();
		}

		//String originalFilename = file.getOriginalFilename();
		//String ext = originalFilename.substring(originalFilename.lastIndexOf(".")+1,originalFilename.length());
		log.debug("ext        : "+ ext);
		
		String fileName =  System.currentTimeMillis()+"."+ext;
		
		log.debug("newPath       :"+newPath);
		log.debug("fileName      :"+fileName);

		try{
			File saveFile = new File(newPath.concat(fileName));
			if(!saveFile.exists())
				saveFile.createNewFile();
			FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(saveFile));
		}catch (IOException e) {
			throw new Exception(e.getMessage());
		}
		
		returnPath = path.concat(pathTemp).concat(fileName);
		log.debug("returnPath    :"+returnPath);
		return returnPath;
	}
	
	public static HashMap<String, Object> saveFile(String folder, MultipartFile file, String ext, String editerFolderName) throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMdd");
		
		System.out.println("path : "+path);
		
		String pathTemp = editerFolderName.concat(folder).concat("/").concat(formatter.format(calendar.getTime()).concat("/"));
		
		String newPath = path.concat(pathTemp);
		
		File dir = new File(newPath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		
		//String originalFilename = file.getOriginalFilename();
		//String ext = originalFilename.substring(originalFilename.lastIndexOf(".")+1,originalFilename.length());
		log.debug("ext        : "+ ext);
		
		String fileName =  System.currentTimeMillis()+"."+ext;
		
		log.debug("newPath       :"+newPath);
		log.debug("fileName      :"+fileName);
		
		try{
			File saveFile = new File(newPath.concat(fileName));
			if(!saveFile.exists())
				saveFile.createNewFile();
			
			FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(saveFile));
		}catch (IOException e) {
			throw new Exception(e.getMessage());
		}
		
		map.put("path", pathTemp);
		map.put("fileName", fileName);
		
		return map;
	}

	public static String saveFile2(String folder, MultipartFile file, String changeFileName) throws Exception{
		String returnPath = "";

		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMdd");

		String pathTemp = folder.concat("/").concat(formatter.format(calendar.getTime()).concat("/"));
		String newPath = path.concat(pathTemp);

		File dir = new File(newPath);
		if(!dir.exists()){
			dir.mkdirs();
		}

		log.debug("newPath          :"+newPath);
		log.debug("changeFileName   :"+changeFileName);

		try{
			File saveFile = new File(newPath.concat(changeFileName));
			if(!saveFile.exists())
				saveFile.createNewFile();
			FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(saveFile));
		}catch (IOException e) {
			throw new Exception(e.getMessage());
		}

		returnPath = pathTemp.concat(changeFileName);
		log.debug("returnPath    :"+returnPath);
		return returnPath;
	}

	public static String saveFile3(String folder, MultipartFile file, String changeFileName) throws Exception{
		String returnPath = "";

		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMdd");

		String pathTemp = folder.concat("/").concat(formatter.format(calendar.getTime()).concat("/"));
		String newPath = path.concat(pathTemp);

		File dir = new File(newPath);
		if(!dir.exists()){
			dir.mkdirs();
		}

		log.debug("newPath          :"+newPath);
		log.debug("changeFileName   :"+changeFileName);

		try{
			File saveFile = new File(newPath.concat(changeFileName));
			if(!saveFile.exists())
				saveFile.createNewFile();
			FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(saveFile));
		}catch (IOException e) {
			throw new Exception(e.getMessage());
		}

		returnPath = pathTemp;
		log.debug("returnPath    :"+returnPath);
		return returnPath;
	}

	public static HashMap<String, Object> saveAttachments(String folder, MultipartFile file) throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		String returnPath = "";
		
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMdd");
		
		String pathTemp = folder.concat("/").concat(formatter.format(calendar.getTime()).concat("/"));
		String newPath = path.concat("/").concat(pathTemp);
		
		File dir = new File(newPath);
		if(!dir.exists()){
			dir.mkdirs();
		}

		String originalFilename = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf('.'));
		String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1,file.getOriginalFilename().length());
		log.debug("originalFilename :"+ originalFilename);

		String fileName =  originalFilename.concat("_").concat(String.valueOf(System.currentTimeMillis())).concat(".").concat(ext);
		//String fileName = IdUtil.getFileNm() + (".").concat(ext);	//저장될 파일 명
		
		log.debug("newPath          :"+newPath);
		log.debug("fileName         :"+fileName);
		String pathFile = newPath.concat(fileName);
		log.debug("pathFile         :" + pathFile);
		try{
			File saveFile = new File(pathFile);
			if(!saveFile.exists())
				saveFile.createNewFile();
			FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(saveFile));
		}catch (IOException e) {
			throw new Exception(e.getMessage());
		}
		
		// 리턴할 파일 경로 추출
		returnPath = pathTemp.concat(fileName);
		//returnPath = folder.concat("/").concat(fileName);
		log.debug("returnPath       :"+returnPath);
		
		map.put("msgCode", Constants.OK);
		map.put("filePath", returnPath);
		map.put("fileName", fileName);
		map.put("originFileName", originalFilename.concat(".").concat(ext));
		
		return map;
	}
	
	
	public static void removeDir(String path){

		File[] listFile = new File(path).listFiles(); 

		try{
			if(listFile.length > 0){
				for(int i = 0 ; i < listFile.length ; i++){
					if(listFile[i].isFile()){
						listFile[i].delete(); 
					}else{
						removeDir(listFile[i].getPath());
					}
					listFile[i].delete();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
}
