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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



/** 
* 1. 기능 : 파일 이동 및 삭제
* 2. 처리 개요 : RenameTo/ Delete
* 3. 주의사항 
*
* @author  : 
* @version : v 1.0.0
* @see : 관련 기능을 참조
* @since   : 
*  : 
*/
public class FileUtils 
{ 
	public static ArrayList<String> fileList = new ArrayList<String>();
	public static List findFileList(String path){
		
		try {
			subDirList(path);
		} catch (Exception 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();

		if(mFileList.length < 1 &&path.endsWith("upload")){
			throw new Exception (new Date() +" | At SubDirList ]\t No List in Directory !!");			
		}
		try{			
			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){
			FileInputStream fis = new FileInputStream(oldFile);
			FileOutputStream fos = new FileOutputStream(newFile);
			
			int data = 0;
			while((data =fis.read()) != -1){
				fos.write(data);
			}
			fis.close();
			fos.close();
			oldFile.delete();
			isMoved = true;
		}
				
		return true;
	}
   

}

