/**
 * 文件名：FileUtil.java
 * 描述：文件工具类
 * 包名：cn.com.kmlt.monstarBase.utils.file
 * 作者：WENJQ
 * 创建日期：2016年05月26日
 * 
 */

package com.mgq.base.utils.file;

import android.os.Environment;
import android.text.TextUtils;

import com.mgq.base.utils.logger.Logger;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class FileUtil {
	private static final String TAG = "FileUtil";

	/**
	 * 
	 * getFileType:获取文件类型 <br/>
	 *
	 * @author WENJQ
	 * @param file java.io.File Example
	 * @return fileType: A String type of fileType
	 */
	public static String getFileType(File file) {
		String fileType = "";
		if (file == null) {
			return fileType;
		}
		String fileTotalName = file.getName();

		int splitIndex = fileTotalName.lastIndexOf(".");
		if (splitIndex != -1) {
			fileType = fileTotalName.substring(splitIndex + 1);
		}
		return fileType;
	}

	/**
	 * 
	 * getFileName:获取文件名称，不含文件类型. <br/>
	 *
	 * @author WENJQ
	 * @param file java.io.File example
	 * @return A String type of file name
	 */
	public static String getFileName(File file) {
		String fileName = "";
		if (file == null) {
			return fileName;
		}
		String fileTotalName = file.getName();

		int splitIndex = fileTotalName.lastIndexOf(".");
		if (splitIndex != -1) {
			fileName = fileTotalName.substring(0, splitIndex);
		}
		return fileName;
	}

	/**
	 *
	 * getFileName:获取文件名称，不含文件类型. <br/>
	 *
	 * @author WENJQ
	 * @param file java.io.File example
	 * @return A String type of file name
	 */
	public static String getFileName(String filePath) {
		String fileName = "";
		if (filePath == null || filePath.isEmpty()) {
			return fileName;
		}

		int splitIndex = filePath.lastIndexOf("/");
		if (splitIndex != -1) {
			fileName = filePath.substring(splitIndex + 1);
		}
		return fileName;
	}

	/**
	 * 通过提供的文件名在默认路径下生成文件
	 * 
	 * @param fileName
	 *            文件的名称
	 * @return 生成的文件
	 * @throws IOException
	 */
	public static File createFile(String filePath, boolean isNextPath) {
		if (TextUtils.isEmpty(filePath)) {
			Logger.e(TAG, "in method createFile, filePath is null");

			return null;
		}

		String folderPath = filePath.substring(0, filePath.lastIndexOf("/"));
		File folder = getFileByPath(folderPath);
		boolean isOk = folder.mkdirs();
		File file = getFileByPath(filePath);

		if (file.exists()) {
			file.delete();
		}


		try {
			file.createNewFile();
		} catch (Exception e) {
			Logger.e(TAG, "create file fail, filePath = " + filePath);
		}
		return file;
	}

	/**
	 * 删除路径指向的文件
	 * 
	 * @param fileName
	 *            文件的名称
	 * @return true删除成功，false删除失败
	 */
	public static boolean deleteFile(String filePath) {
		File file = getFileByPath(filePath);
		if (file.isFile()) {
			return file.delete();
		}
		return false;
	}

	public static File getFileByPath(String filePath) {
		filePath = filePath.replaceAll("\\\\", "/");
		boolean isSdcard = false;
		int subIndex = 0;
		if (filePath.indexOf("/sdcard") == 0) {
			isSdcard = true;
			subIndex = 7;
		} else if (filePath.indexOf("/mnt/sdcard") == 0) {
			isSdcard = true;
			subIndex = 11;
		}

		if (isSdcard) {
			if (isExistSdcard()) {
				File sdCardDir = Environment.getExternalStorageDirectory();
				String fileName = filePath.substring(subIndex);
				return new File(sdCardDir, fileName);
			} else if (isEmulator()) {
				File sdCardDir = Environment.getExternalStorageDirectory();
				String fileName = filePath.substring(subIndex);
				return new File(sdCardDir, fileName);
			}
			return null;
		} else {
			return new File(filePath);
		}
	}

	private static boolean isExistSdcard() {
		if (!isEmulator()) {
			return Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED);
		}
		return true;
	}

	private static boolean isEmulator() {
		return android.os.Build.MODEL.equals("sdk");
	}

	public static boolean isFileExist(String path) {
		File file;
		if (path != null && !path.equals("")) {
			file = new File(path);
			if (file.isFile() && file.exists() && file.length()>0) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}

	}

	/**
	 * 计算位数
	 * 
	 * @param str
	 * @return
	 */
	public static int calculatePlaces(String str) {
		int m = 0;
		char arr[] = str.toCharArray();
		for (int i = 0; i < arr.length; i++) {
			char c = arr[i];
			if ((c >= 0x0391 && c <= 0xFFE5)) // 中文字符
			{
				m = m + 2;
			} else // 英文字符 和 数字
			{
				m = m + 1;
			}
		}
		return m;
	}

	// 2 * 1024* 1024 * 1024-----> 2.00G
	public static String bytesToString(long bytes) {
		long gb = (bytes) / 1024 / 1024 / 1024;
		DecimalFormat df = new DecimalFormat("###.00");
		String strResult = "";
		if (gb <= 0) {
			long mb = (bytes) / 1024 / 1024;
			if (mb <= 0) {
				strResult = df.format(((double) bytes) / 1024) + "KB";
			} else {
				strResult = df.format(((double) bytes) / 1024 / 1024) + "MB";
			}
		} else {
			strResult = df.format(((double) bytes) / 1024 / 1024 / 1024) + "GB";
		}

		if (strResult.indexOf(".") == 0) {
			return "0" + strResult;
		} else {
			return strResult;
		}
	}
	
    public static void saveToFile(String[] sourceName, String targetName,
            String[] name) throws IOException {
        File file = new File(targetName);
        if (!file.exists())
            file.createNewFile();

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(9);

        DataOutputStream dos = new DataOutputStream(zos);
        for (int i = 0; i < sourceName.length; i++) {
            zos.putNextEntry(new ZipEntry(name[i]));
            File sourceFile = new File(sourceName[i]);
            FileInputStream fis = new FileInputStream(sourceFile);
            byte bytes[] = new byte[fis.available()];
            fis.read(bytes, 0, bytes.length);
            dos.write(bytes);

            if (fis != null)
                fis.close();

        }
        if (dos != null)
            dos.close();
    }
    
    public static void doCopyFile(String srcFilePath, String desFilePath) {
		File srcFile = new File(srcFilePath);
		File destFile = new File(desFilePath);
		FileInputStream input = null;
		FileOutputStream output;
        try {
        	input= new FileInputStream(srcFile);
            output = new FileOutputStream(destFile);
            try {
            	byte[] buffer = new byte[4096];
                int n = 0;
                while (-1 != (n = input.read(buffer))) {
                    output.write(buffer, 0, n);
                }
            } finally {
            	try {
                    if (output != null) {
                        output.close();
                    }
                } catch (IOException ioe) {
                    // ignore
                }
            }
        }catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
        	try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException ioe) {
                // ignore
            }
        }
	}
    
    public static void doCopyFile(File srcFilePath, String desFilePath) {

		File destFile = new File(desFilePath);
		FileInputStream input = null;
		FileOutputStream output;
        try {
        	input= new FileInputStream(srcFilePath);
            output = new FileOutputStream(destFile);
            try {
            	byte[] buffer = new byte[4096];
                int n = 0;
                while (-1 != (n = input.read(buffer))) {
                    output.write(buffer, 0, n);
                }
            } finally {
            	try {
                    if (output != null) {
                        output.close();
                    }
                } catch (IOException ioe) {
                    // ignore
                }
            }
        }catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
        	try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException ioe) {
                // ignore
            }
        }
	}
}
