package com.beanpodtech.allinone.utils;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
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.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class FileUtil {

    private final static String TAG = "lhs_FileUtil";

    /**
     * 删除单个文件
     *
     * @param filePath 被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public boolean deleteFile(String filePath) {
        if (filePath == null || filePath.equals("")) {
            Log.e(TAG, "deleteFile filePath is null");
            return false;
        }
        File file = new File(filePath);
        try {
            if (file.isFile() && file.exists()) {
                return file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除文件夹以及目录下的文件
     *
     * @param filePath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public boolean deleteDirectory(String filePath) {
        if (filePath == null || filePath.equals("")) {
            Log.e(TAG, "deleteDirectory filePath is null");
            return false;
        }
        boolean flag = false;
        //如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        //遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                //删除子文件
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            } else {
                //删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            }
        }
        if (!flag) {
            return false;
        }
        //删除当前空目录
        return dirFile.delete();
    }

    public boolean createFile(File file) {
        try {
            if (file.getParentFile().exists()) {
                Log.i(TAG, "createFile" + file.getAbsolutePath());
                file.createNewFile();
            } else {
                //创建目录之后再创建文件
                createDir(file.getParentFile().getAbsolutePath());
                file.createNewFile();
                Log.i(TAG, "createFile" + file.getAbsolutePath());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean createDir(String dirPath) {
        //因为文件夹可能有多层，比如:  a/b/c/ff.txt  需要先创建a文件夹，然后b文件夹然后...
        try {
            File file = new File(dirPath);
            if (file.getParentFile().exists()) {
                Log.i(TAG, "createDir" + file.getAbsolutePath());
                file.mkdir();
            } else {
                createDir(file.getParentFile().getAbsolutePath());
                Log.i(TAG, "createDir" + file.getAbsolutePath());
                file.mkdir();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean writeFile(byte[] bitMap, String fileName) {
        if (bitMap == null || bitMap.length < 1 || fileName == null || fileName.equals("")) {
            Log.e(TAG, "writeFile paras is invalid");
            return false;
        }
        try {

            File saveFile = new File(fileName);
            if (!saveFile.exists()) {
                Log.e(TAG, "writeFile file is not exists");
                return false;
            }

            FileOutputStream outStream = new FileOutputStream(saveFile);
            try {
                outStream.write(bitMap);
            } catch (IOException ex) {
                Log.e(TAG, "IO");
                ex.printStackTrace();
                return false;
            }
            try {
                outStream.close();
            } catch (IOException ex) {
                Log.e(TAG, "IO");
                ex.printStackTrace();
                return false;
            }
        } catch (FileNotFoundException ex) {
            Log.e(TAG, "FileNotFoundException");
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    public byte[] readFile(String fileName) {
        if (fileName == null || fileName.equals("")) {
            Log.e(TAG, "readFile paras is invalid");
            return null;
        }
        try {
            FileInputStream fis = new FileInputStream(fileName);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            return b;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String readFile() {
        try {
            FileInputStream fis = new FileInputStream("/sdcard/test.txt");

            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            StringBuilder sb = new StringBuilder("");
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //移除文件，获取文件时间与当前时间对比，我这时间定位5天，删除五天前的文件
    public static void removeFileByTime(String dirPath) {
        //获取目录下所有文件
        List<File> allFile = getDirAllFile(new File(dirPath));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //获取当前时间
        Date end = new Date(System.currentTimeMillis());
        try {
            end = dateFormat.parse(dateFormat.format(new Date(System.currentTimeMillis())));
        } catch (Exception e) {
            Log.d(TAG, "dataformat exeption e " + e.toString());
        }
        Log.d(TAG, "getNeedRemoveFile  dirPath = " + dirPath);
        for (File file : allFile) {//ComDef
            try {
                //文件时间减去当前时间
                Date start = dateFormat.parse(dateFormat.format(new Date(file.lastModified())));
                long diff = end.getTime() - start.getTime();//这样得到的差值是微秒级别
                long days = diff / (1000 * 60 * 60 * 24);
                if (Contants.BITMAP_MAX_KEEP_TIME <= days) {
                    deleteFile(file);
                }

            } catch (Exception e) {
                Log.d(TAG, "dataformat exeption e " + e.toString());
            }
        }
    }

    //删除文件夹及文件夹下所有文件
    public static void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            file.delete();
        } else if (file.exists()) {
            file.delete();
        }
    }

    //获取指定目录下一级文件
    public static List<File> getDirAllFile(File file) {
        List<File> fileList = new ArrayList<>();
        File[] fileArray = file.listFiles();
        if (fileArray == null) {
            return fileList;
        }
        for (File f : fileArray) {
            fileList.add(f);
        }
        fileSortByTime(fileList);
        return fileList;
    }

    //对文件进行时间排序
    public static void fileSortByTime(List<File> fileList) {
        Collections.sort(fileList, new Comparator<File>() {
            @Override
            public int compare(File p1, File p2) {
                if (p1.lastModified() < p2.lastModified()) {
                    return -1;
                }
                return 1;
            }
        });
    }

    //复制加密文件到内存中并获取绝对路径
    public static String getAssetsCacheFile(Context context, String fileName) {
        File cacheFile = new File(context.getCacheDir(), fileName);
        try {
            InputStream inputStream = context.getAssets().open(fileName);
            try {
                FileOutputStream outputStream = new FileOutputStream(cacheFile);
                try {
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) {
                        outputStream.write(buf, 0, len);
                    }
                } finally {
                    outputStream.close();
                }
            } finally {
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cacheFile.getAbsolutePath();
    }

    //判断加密文件是否已存在
    public static boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile, "encryptedApp.dat");
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static String getFileAbsolutePath(String strFile) {
        File f = new File(strFile, "encryptedApp.dat");
        return f.getAbsolutePath();
    }

    public static String getPath(Context context, String EnvironmentType) {
        String path;
//        Environment.DIRECTORY_DOCUMENTS
        if (Build.VERSION.SDK_INT > 28) {
            path = context.getExternalFilesDir(EnvironmentType).getPath();
        } else {
            path = Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return path;
    }

    public static String getPathWithDirname(Context context, String EnvironmentType, String dirName) {
        String path = getPath(context, EnvironmentType);
        return path + File.separator + dirName;
    }

}