package com.udapsoft.waf.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.StringTokenizer;

public class FileUtil
{
    /**
     * 특정 Dirctory 존재 여부 check
     * 만약 Directory 없을 경우 생성
     * @param       Path        경로
     * @return  String  path를 다시 return 한다.. <br>
     *                  /www//kkk/dd.html  -> /www/kkk/dd.html 형태로 return
     */
    public static String chkDirectory(String fname) throws Exception {
        String seperator = "";
        
        if( fname.indexOf("/") < 0 ) {
            // unix type
            seperator = "\\";
        }
        else {
            // windows type
            seperator = "/";
        }
        
        StringTokenizer st = new StringTokenizer(fname, seperator);

        String tVar = "";

        int stCnt = st.countTokens();
        
        // unix 계열경우
        if ((fname.indexOf(":") < 0) && (fname.startsWith("/")))
            tVar = "/";
        

        for (int i = 0; i < stCnt; i++) {

            if (i != 0)
                tVar += seperator;
            
            tVar += st.nextToken();

            // 확장자가 나오면 return true
            if (tVar.indexOf(".") != -1) return tVar;
            
            // window경우
            if ((i == 0) && ( tVar.indexOf(":") > -1))
                continue;

            if (!mkDir(tVar)) return null;
        }
        
        return fname;
    }


    /**
     * 특정 경로에 존재하는 FileList를 가져옴
     *
     * @param       Path        경로
     */
    public static String[] getFileList(String path) throws Exception {

        String[] FILE_LIST = null;

        File dir = new File(path);
        if (dir.isDirectory())
            FILE_LIST = dir.list();

        return FILE_LIST;
    }


    /**
     * File 여부 체크
     *
     * @param       Path        경로
     */
    public static boolean isFile(String path) throws Exception  {

        File tFile = new File(path);
        return tFile.isFile() ;
    }


    /**
     * Directory 여부 체크
     *
     * @param       Path        경로
     */
    public static boolean isDir(String path) throws Exception  {

        File dir = new File(path);
        if( dir.exists() && dir.isDirectory() )
            return true;
        return false;
    }


    /**
     * Directory 생성
     *
     * @param       Path        경로
     */
    public static boolean mkDir(String path) throws Exception {

        if (path.length() < 1)
            return true;

        File dir = new File(path);
        if (dir.exists() && dir.isDirectory())
            return true;
        else
            return dir.mkdir();
    }

    /**
     * file delete
     *
     * @param       Path        경로
     */
    public static boolean delFile(String path) throws Exception {

        File tFile = new File(path);
        if (tFile.exists() && tFile.isFile())
            return tFile.delete();
        else
            return false;
    }

    /**
     * file delete
     *
     * @param       Path        경로
     */
    public static boolean delDir(String path)  throws Exception {

        File tFile = new File(path);
        
        if (tFile.isDirectory())
        {
            String[] fileNames = tFile.list();
            for (int i = 0; i < fileNames.length; i++)
            {
                if (fileNames[i] == null || fileNames[i].equals(""))
                    continue;
                File f = new File(path + File.separator + fileNames[i]);
                if (f.exists() && f.isFile())
                {
                    f.delete();
                }
                else if (f.exists() && f.isDirectory())
                {
                    delDir(path + File.separator + fileNames[i]);
                }
            }
            return tFile.delete();
        }
        else
        {
            return false;
        }
    }

    public static byte[] getBytesFromFile(String path) throws IOException  {

        File file = new File(path);
        
        InputStream is = new FileInputStream(file);
    
        // Get the size of the file
        long length = file.length();
    
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
    
        // Read in the bytes
        int offset = 0;
        int numRead = 0;

        while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) 
        {
            offset += numRead;
        }
    
        // Ensure all the bytes have been read in
        if (offset < bytes.length) 
        {
            throw new IOException("Could not completely read file " + file.getName());
        }
    
        // Close the input stream and return bytes
        is.close();
        
        return bytes;
    }

    public static String getExtension(String filename) throws Exception
    {
        String extension = "";
        int k = filename.indexOf(".");
        if( k > -1 )
            extension = filename.substring(k + 1, filename.length());
        return extension ;
    }

    /**
     * Method copyFile.
     * @param argSource
     * @param argTarget
     * @return boolean
     * @throws Exception
     */
    public static boolean copyFile(String argSource, String argTarget) throws Exception
    {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        byte[] temp = new byte[4096];
        try {
            fis = new FileInputStream(argSource);

            if( fis == null )
                throw new Exception("argSource or FileInputStream is null : " + argSource);

            fos = new FileOutputStream(argTarget);

            int offset = 0;
            int len = 0;
            while( (len = fis.read(temp) ) != -1 ) {
                fos.write(temp, 0, len);
                offset += len;
            } 
            return true;
        }
        finally
        {
            if( fis != null ) fis.close();
            if( fos != null ) fos.close();
        }
    }

    /**
     * Method rename.
     * @param src
     * @param target
     * @return boolean
     * @throws Exception
     */
    public static boolean rename(String src, String target) throws Exception
    {
        return (new File(src)).renameTo(new File(target));
    }
}
