package com.xuqm.base.common;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.xuqm.base.App;
import com.xuqm.base.BuildConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class FileHelper {


    public static String getRootFilePath() {
        return App.getInstance().getExternalFilesDir(null).getPath() +
                File.separator +
                BuildConfig.APP_ID +
                File.separator;
    }

    /**
     * 根据路径创建文件夹
     *
     * @param filePath
     * @return
     */
    public static boolean createDirectory(String filePath) {
        if (ToolsHelper.isNull(filePath)) {
            return false;
        }

        File file = new File(filePath);

        if (file.exists() && file.isDirectory()) {
            return true;
        }

        return file.mkdirs();

    }

    public static void delete(String path) {
        LogHelper.e(String.format("开始删除文件::%s", path));
        File file = new File(path);
        if (!file.exists()
                || !file.isFile())
            return;
        file.delete();

    }
    public static void delete(File file) {
        LogHelper.e(String.format("开始删除文件::%s", file.getAbsoluteFile()));
        if (!file.exists()
                || !file.isFile())
            return;
        file.delete();

    }

    public static String getVoicePath() {
        String path = getRootFilePath() +
                "voice" +
                File.separator;

        return createDirectory(path) ? path : "";
    }
    public static String getImagePath() {
        String path = getRootFilePath() +
                "image" +
                File.separator;

        return createDirectory(path) ? path : "";
    }

    public static String getAppPath() {
        String path = getRootFilePath() +
                "apps" +
                File.separator;
        LogHelper.e(path);

        return createDirectory(path) ? path : "";
    }
    public static String getDownloadPath() {
        String path = getRootFilePath() +
                "download" +
                File.separator;
        LogHelper.e(path);

        return createDirectory(path) ? path : "";
    }

    /**
     * 读取assets文件夹的文件
     *
     * @param strFileName 文件名，包含assets后面的路径
     * @return 文件内容
     */
    public static String readJSON(String strFileName) {
        String strResult = "";
        try (InputStream is = App.getInstance().getAssets().open(strFileName)) {
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            strResult = new String(buffer, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            LogHelper.e("readJson", ex);
        }
        return strResult;
    }

    public static String getBitmapFilePath(String path, String suffix) {

        String pathStr = getRootFilePath() + "images" + File.separator + path + File.separator;
        createDirectory(pathStr);

        return pathStr + UUID.randomUUID() + "." + suffix;
    }

    /**
     * 保存图片到本地
     *
     * @param bitmap   图片
     * @param filePath 保存到的文件 png
     * @return 状态
     */
    public static String saveBitmap(Bitmap bitmap, String filePath) {
        if (bitmap == null)
            return "";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(filePath));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    public void installAPK(String filePath) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 广播里面操作需要加上这句，存在于一个独立的栈里
        intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
        App.getInstance().startActivity(intent);
    }

    public static void openFile(Context activity, File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 设置intent的Action属性
        intent.setAction(Intent.ACTION_VIEW);
        // 获取文件file的MIME类型
        String type = getMIMEType(file);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        // 设置intent的data和Type属性。
        intent.setDataAndType(/* uri */FileHelper.getFileUri(file), type);
        activity.startActivity(intent);
    }

    public static Uri getFileUri(@NonNull File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(AppManager.getInstance().getActivity(), BuildConfig.APP_ID + ".fileprovider", file);
        } else {
            return Uri.fromFile(file);
        }
    }

    private static String[][] MIME_MapTable = new String[][]{{".3gp", "video/3gpp"}, {".apk", "application/vnd.android.package-archive"}, {".asf", "video/x-ms-asf"}, {".avi", "video/x-msvideo"}, {".bin", "application/octet-stream"}, {".bmp", "image/bmp"}, {".c", "text/plain"}, {".class", "application/octet-stream"}, {".conf", "text/plain"}, {".cpp", "text/plain"}, {".doc", "application/msword"}, {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, {".xls", "application/vnd.ms-excel"}, {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, {".exe", "application/octet-stream"}, {".gif", "image/gif"}, {".gtar", "application/x-gtar"}, {".gz", "application/x-gzip"}, {".h", "text/plain"}, {".htm", "text/html"}, {".html", "text/html"}, {".jar", "application/java-archive"}, {".java", "text/plain"}, {".jpeg", "image/jpeg"}, {".jpg", "image/jpeg"}, {".eucppic", "image/jpeg"}, {".js", "application/x-javascript"}, {".log", "text/plain"}, {".m3u", "audio/x-mpegurl"}, {".m4a", "audio/mp4a-latm"}, {".m4b", "audio/mp4a-latm"}, {".m4p", "audio/mp4a-latm"}, {".m4u", "video/vnd.mpegurl"}, {".m4v", "video/x-m4v"}, {".mov", "video/quicktime"}, {".mp2", "audio/x-mpeg"}, {".mp3", "audio/x-mpeg"}, {".mp4", "video/mp4"}, {".mpc", "application/vnd.mpohun.certificate"}, {".mpe", "video/mpeg"}, {".mpeg", "video/mpeg"}, {".mpg", "video/mpeg"}, {".mpg4", "video/mp4"}, {".mpga", "audio/mpeg"}, {".msg", "application/vnd.ms-outlook"}, {".ogg", "audio/ogg"}, {".pdf", "application/pdf"}, {".png", "image/png"}, {".pps", "application/vnd.ms-powerpoint"}, {".ppt", "application/vnd.ms-powerpoint"}, {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, {".prop", "text/plain"}, {".rc", "text/plain"}, {".rmvb", "audio/x-pn-realaudio"}, {".rtf", "application/rtf"}, {".sh", "text/plain"}, {".tar", "application/x-tar"}, {".tgz", "application/x-compressed"}, {".txt", "text/plain"}, {".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"}, {".wmv", "audio/x-ms-wmv"}, {".wps", "application/vnd.ms-works"}, {".xml", "text/plain"}, {".z", "application/x-compress"}, {".zip", "application/x-zip-compressed"}, {"", "*/*"}};

    public static String getMIMEType(File file) {
        String type = "*/*";
        String fName = file.getName();
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        } else {
            String end = fName.substring(dotIndex, fName.length()).toLowerCase();
            if (end == "") {
                return type;
            } else {
                for (int i = 0; i < MIME_MapTable.length; ++i) {
                    if (end.equals(MIME_MapTable[i][0])) {
                        type = MIME_MapTable[i][1];
                    }
                }

                return type;
            }
        }
    }

}
