package com.eactive.eai.rms.onl.common.util; 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.eactive.eai.rms.onl.loader.controller.HistoryController;



/** 
* 1. 기능 : 파일 이동 및 삭제
* 2. 처리 개요 : RenameTo/ Delete
* 3. 주의사항 
*
* @author  : 
* @version : v 1.0.0
* @see : 관련 기능을 참조
* @since   : 
*  : 
*/
public class SimpleFileUtils 
{ 
	private static final Logger logger = Logger.getLogger(HistoryController.class);
	public static ArrayList<String> fileList = new ArrayList<String>();
	public static List findFileList(String path){
		
		try {
			subDirList(path);
		} catch (Exception e) {
			logger.warn(e);
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		return fileList;
	}
	
	public static void subDirList(String path) throws Exception{

		File dir = new File(path);
		if(!dir.exists()){
			throw new Exception(new Date() +" | At SubDirList ] No File");
			
		}
		File[] mFileList = dir.listFiles();
		//취약점코드 수정 2019.08.22 SW
		if(mFileList != null && (mFileList.length < 1 &&path.endsWith("upload"))){
			throw new Exception (new Date() +" | At SubDirList ]\t No List in Directory !!");			
		}
		try{
			//취약점코드 수정 2019.08.22 SW
			if(mFileList != null){
				for(int i = 0; i < mFileList.length; i++){
					File file = mFileList[i];
					if(file.isFile()){					
						fileList.add(file.getAbsolutePath().toString());
					}else if(file.isDirectory()){
						subDirList(file.getCanonicalPath().toString());
					}
				}
			}
		}catch(Exception e){
			throw new Exception(new Date()+" | At subDirList ]\t Could not create File List ");
		}
		
	}
	
	public static Boolean moveFile(String from,String to, String oldFileName, String newFileName) throws Exception{
		//String path = hm.get("serviceType")+File.separator+hm.get("bzwkDstcd")+File.separator+hm.get("cmd")+File.separator+hm.get("fileName");
		Boolean isMoved = false;
		//File path = new File(from);
		File newPath = new File(to);
		
		File oldFile = new File(from+oldFileName);
		File newFile = new File(to+newFileName);
		//File savePath = new File(newPath.substring(0,newPath.lastIndexOf(File.separator)));
		
		if(!newPath.exists()){
			newPath.mkdirs();
		}
		if(newFile.exists()){
			boolean t = newFile.delete();		
			if(!t){
				throw new Exception(new Date()+" | At moveFile ] "+newFileName +" is already exist");
			}
		}
		
		isMoved = oldFile.renameTo(newFile);
		
		if(!isMoved){
			try {
				Files.copy(oldFile.toPath(), newFile.toPath());
			}
			catch(Exception ex) {
				logger.error("Move file error", ex);
				return false;
			}
			finally {
				if(oldFile != null) 
					try { 
						oldFile.delete(); 
					} catch(Exception ee) {
						logger.error(" error : ", ee); 
					}
			}
		}
		return true;
	}
   
	@SuppressWarnings("resource")
	public static Boolean moveFileChannel(String from,String to, String oldFileName, String newFileName) throws Exception{
		Boolean isMoved = false;
		//File path = new File(from);
		File newPath = new File(to);
		
		File oldFile = new File(from+oldFileName);
		File newFile = new File(to+newFileName);

		
		if(!newPath.exists()){
			newPath.mkdirs();
		}
		if(newFile.exists()){
			boolean t = newFile.delete();		
			if(!t){
				throw new Exception(new Date()+" | At moveFile ] "+newFileName +" is already exist");
			}
		}
		
		isMoved = oldFile.renameTo(newFile);
		
		FileChannel srcChannel = null;
		FileChannel tgtChannel = null;
		
		if(!isMoved){
			try {
				srcChannel = new FileInputStream(oldFile).getChannel();
				tgtChannel = new FileOutputStream(newFile).getChannel();
				tgtChannel.transferFrom(srcChannel, 0, srcChannel.size());
			}
			catch(Exception ex) {
				logger.error("Move file error", ex);
				return false;
			}
			finally {
				if(srcChannel != null) try { srcChannel.close(); } catch(Exception ee) {}
				if(tgtChannel != null) try { tgtChannel.close(); } catch(Exception ee) {}
			}
		}
		return true;
	}
    public static void deleteFolder(String path){
    	File folder = new File(path);
    	try{
    		if(folder.exists()){
    			File[] folderList = folder.listFiles(); //파일리스트 얻어오기
    			if (folderList != null) {
    				for(File f : folderList){
    					if (f.isFile()){
    						//file 삭제
    						f.delete();
    						logger.debug("file("+f.getName()+") delete");
    						//System.out.println("file("+f.getName()+") delete");
    					}else{
    						//folder 삭제
    						deleteFolder(f.getPath());
    						logger.debug("folder("+f.getName()+") delete");
    						//System.out.println("folder("+f.getName()+") delete");
    					}
    				}
    			}
    			folder.delete(); //폴더삭제
    		}
    	}catch(Exception e){
    		logger.error("delete folder error", e);
    	}
    }
//    public static void main(String [] args) throws Exception{ //취약점소스 수정 2020.08.24
//    	deleteFolder("C:\\fslog\\eai\\test");
//    } 
}

