package com.mints.goodmoney.utils;

import android.graphics.Bitmap;
import android.os.Environment;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;

/**
 * 文件操作UTILS
 *
 * @author renjl
 * @time Apr 18, 2015 10:04:37 AM
 * @explain
 */
public class FileUtils {


    /**
     * 获取SD卡的根目录
     *
     * @return null：不存在SD卡
     */
    public static File getRootDirectory() {
        boolean isAvailable = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
        return isAvailable ? Environment.getExternalStorageDirectory() : null;
    }

    /**
     * 判断文件是否存在
     *
     * @param fileURl
     * @return
     */
    public static boolean fileIsExists(String fileURl) {
        try {
            File f = new File(fileURl);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 判断文件是否存在 有则删除
     *
     * @param fileURl
     */
    public static void fileIsExistsAndDel(String fileURl) {
        try {
            File f = new File(fileURl);
            if (f.exists()) {
                if (f.isFile())
                    f.delete();
            }
        } catch (Exception e) {
        }
    }

    /**
     * 创建文件
     *
     * @param path
     * @param filename
     * @return
     */
    public static File createAttachFile(String path, String filename) {
        File attachFile = new File(path, filename);
        if (!attachFile.exists()) {
            try {
                attachFile.getParentFile().mkdirs();
                attachFile.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return attachFile;
    }

    /**
     * 获得指定文件的byte数组
     *
     * @param filePath
     * @return
     */
    public byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }


    /**
     * 根据byte数组，生成文件
     *
     * @param bfile
     * @param filePath
     * @param fileName
     */
    public void getFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            //判断是否有这个文件如果有的话则删除
            fileIsExistsAndDel(filePath + "\\" + fileName);
            file = new File(filePath + "\\" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据地址获得数据的字节流并转换成大小
     *
     * @param strUrl 网络连接地址
     * @return
     */
    public static String getFileSizeByUrl(String strUrl) {
        InputStream inStream = null;
        ByteArrayOutputStream outStream = null;
        String size = "";
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            inStream = conn.getInputStream();

            outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] bt = outStream.toByteArray();

            if (null != bt && bt.length > 0) {
                DecimalFormat df = new DecimalFormat("#.00");
                size = df.format((double) bt.length / 1048576) + "MB";
            } else {
                System.out.println("没有从该连接获得内容");
            }
            inStream.close();
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return size;
    }


    public static String getApkUrlSize(String apkurl) {
        String size = "";
        URL url = null;
        URLConnection uc = null;
        try {
            url = new URL(apkurl);
            uc = url.openConnection();
            size = new DecimalFormat("0.00").format((float) uc.getContentLength() / 1048576);
            size = size + "MB";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    public static File saveBitmapFile(String filePath,String fileName, Bitmap bitmap) {

        File file = createAttachFile(filePath,fileName);

        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
}

