package com.zhaohaoting.framework.utils;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;

/**
 * author：Created by ZHT on 2017/11/1 11:37
 * email：526309416@qq.com
 * desc：主要功能有清除内/外缓存，清除数据库，清除sharedPreference，清除files和清除自定义目录
 */
public class DataCache {

    private static final String CACHE = "CACHE";
    private static final String PIC = "PIC";
    private static final String MUSIC = "MUSIC";
    private static final String MP4 = "MP4";
    private static final String VOICE = "VOICE";
    public static final int SIZETYPE_B = 1;
    public static final int SIZETYPE_KB = 2;
    public static final int SIZETYPE_MB = 3;
    public static final int SIZETYPE_GB = 4;

    /**
     * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * * @param context
     */
    public static void cleanInternalCache(Context context) {
        deleteFilesByDirectory(context.getCacheDir());
    }

    /**
     * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * * @param context
     */
    public static void cleanDatabases(Context context) {
        deleteFilesByDirectory(new File("/data/data/"
                + context.getPackageName() + "/databases"));
    }

    /**
     * * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) * * @param
     * context
     */
    public static void cleanSharedPreference(Context context) {
        deleteFilesByDirectory(new File("/data/data/"
                + context.getPackageName() + "/shared_prefs"));
    }

    /**
     * 按名字清除本应用数据库 * * @param context * @param dbName
     */
    public static void cleanDatabaseByName(Context context, String dbName) {
        context.deleteDatabase(dbName);
    }

    /**
     * 清除/data/data/com.xxx.xxx/files下的内容 * * @param context
     */
    public static void cleanFiles(Context context) {
        deleteFilesByDirectory(context.getFilesDir());
    }

    /**
     * * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param
     * context
     */
    public static void cleanExternalCache(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteFilesByDirectory(context.getExternalCacheDir());
        }
    }

    /**
     * * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/file) * * @param
     * context
     */
    public static void cleanExternalFile(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteFilesByDirectory(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES));
        }
    }

    /**
     * 清除本应用内部缓存(/data/data/com.xxx.xxx/file) * * @param context
     */

    public static void cleanInternalFile(Context context) {
        deleteFilesByDirectory(context.getFilesDir());
    }

    /**
     * 清除自定义路径下的文件，使用需小心，请不要误删。而且只支持目录下的文件删除 * * @param filePath
     */
    public static void cleanCustomCache(String filePath) {
        deleteFilesByDirectory(new File(filePath));
    }

    /**
     * 清除本应用所有的数据 * * @param context * @param filepath
     */
    public static void cleanApplicationData(Context context, String... filepath) {
        cleanInternalCache(context);
        cleanExternalCache(context);
        cleanDatabases(context);
        cleanSharedPreference(context);
        DataCache.cleanExternalFile(context);
        DataCache.cleanInternalFile(context);
        cleanFiles(context);
        for (String filePath : filepath) {
            cleanCustomCache(filePath);
        }

    }

    /**
     * 清除缓存
     *
     * @param context
     */
    public static void clearCacheData(Context context) {
        DataCache.cleanInternalCache(context);
        DataCache.cleanExternalCache(context);
        DataCache.cleanExternalFile(context);
//        DataCache.cleanInternalFile(context);
        DataCache.cleanDatabaseByName(context, "webview.db");
        DataCache.cleanDatabaseByName(context, "webviewCookiesChromium.db");
        DataCache.cleanDatabaseByName(context, "webviewCookiesChromiumPrivate.db");
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的文件
     */
    public static void deleteFilesByDirectory(File file) {
        if (file != null && file.exists()) {
            if (file.isDirectory()) {
                for (File item : file.listFiles()) {
                    deleteFilesByDirectory(item);
                }
            } else {
                file.delete();
            }
        }
    }

    private static String diskCacheRootPath;

    /**
     * @return 获取应用本地磁盘缓存根路径
     */
    public static String getAppDiskCacheRoot(Context context) {
        if (diskCacheRootPath != null) return diskCacheRootPath;
        try {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
                diskCacheRootPath = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath();
            } else {
                diskCacheRootPath = context.getCacheDir().getPath();
            }
        } catch (Exception e) {
            diskCacheRootPath = context.getCacheDir().getPath();
        }
        return diskCacheRootPath;
    }

    public static String getCacheDir(Context context) {
        File cache = new File(getAppDiskCacheRoot(context), CACHE);
        if (!cache.exists()) {
            cache.mkdirs();
        }
        return cache.getAbsolutePath()+ File.separator;
    }

    public static String getPicCacheDir(Context context) {
        File cache = new File(getAppDiskCacheRoot(context), PIC);
        if (!cache.exists()) {
            cache.mkdirs();
        }
        return cache.getAbsolutePath()+ File.separator;
    }

    public static String getVoiceCacheDir(Context context) {
        File cache = new File(getAppDiskCacheRoot(context), VOICE);
        if (!cache.exists()) {
            cache.mkdirs();
        }
        return cache.getAbsolutePath()+ File.separator;
    }

    public static String getMP4CacheDir(Context context) {
        File cache = new File(getAppDiskCacheRoot(context), MP4);
        if (!cache.exists()) {
            cache.mkdirs();
        }
        return cache.getAbsolutePath()+ File.separator;
    }

    public static String getMusicCacheDir(Context context) {
        File cache = new File(getAppDiskCacheRoot(context), MUSIC);
        if (!cache.exists()) {
            cache.mkdirs();
        }
        return cache.getAbsolutePath()+ File.separator;
    }

    /**
     * 转换文件大小,指定转换的类型
     *
     * @param fileS
     * @param sizeType
     * @return
     */
    public static double formetFileSize(long fileS, int sizeType) {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSizeLong = 0;
        switch (sizeType) {
            case SIZETYPE_B:
                fileSizeLong = Double.valueOf(df.format((double) fileS));
                break;
            case SIZETYPE_KB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
                break;
            case SIZETYPE_MB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
                break;
            case SIZETYPE_GB:
                fileSizeLong = Double.valueOf(df
                        .format((double) fileS / 1073741824));
                break;
            default:
                break;
        }
        return fileSizeLong;
    }

    /**
     * 计算缓存大小
     */
    public static String calculateCacheSize(Context context) throws Exception {
        long cacheSize = DataCache.getFileSizes(context.getCacheDir()) + DataCache.getFileSizes(context.getExternalCacheDir()) + DataCache.getFileSizes(context.getFilesDir()) + DataCache.getFileSizes(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES));
        return String.valueOf(DataCache.formetFileSize(cacheSize, DataCache.SIZETYPE_MB)) + "M";
    }

    /**
     * 获取指定文件大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
        }
        return size;
    }


    /**
     * 获取指定文件夹大小
     *
     * @param f
     * @return
     * @throws Exception
     */
    public static long getFileSizes(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i]);
            } else {
                size = size + getFileSize(flist[i]);
            }
        }
        return size;
    }
}
