package com.duben.microtribe.utils;

import android.app.Activity;
import android.app.RecoverableSecurityException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.RequiresApi;

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;
import java.util.ArrayList;

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

    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                Boolean isTrue = file.mkdir();
            }
        } catch (Exception e) {

        }
    }

    public static String getFileSize(String path) {
        File f = new File(path);
        if (!f.exists()) {
            return "0 MB";
        } else {
            long size = f.length();
            return (size / 1024f) / 1024f + "MB";
        }
    }

    /**
     * 获取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;
    }

    /**
     * 创建文件
     *
     * @param path
     * @param filename
     * @return
     */
    public static void deleteFile(String path, String filename) {
        File file = new File(path, filename);
        if (file.exists() && file.isFile()) {
            try {
                file.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除单个文件
     */
    public static Boolean deleteFile(String filePath) {
        File file = new File(filePath);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            file.delete();
            return true;
        } else {
            return false;
        }
    }

    // 删除后更新手机资源文件
    public static void updateFile(String imgPath, Context context) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(new File(imgPath)));
        context.sendBroadcast(intent);
    }

    /**
     * 获得指定文件的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;
    }

    public static String getExtensionName(String filename) {
        if (filename != null) {
            int dot = filename.lastIndexOf('.');
            if (dot > -1 && dot < filename.length() - 1) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    public static boolean deleteImage(String imgPath, Activity activity) {
        ContentResolver resolver = activity.getApplicationContext().getContentResolver();
        Cursor cursor = MediaStore.Images.Media.query(
                resolver,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=?",
                new String[]{imgPath},
                null
        );

        boolean result = false;
        Uri uri;

        if (cursor.moveToFirst()) {
            long id = cursor.getLong(0);
            Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            uri = ContentUris.withAppendedId(contentUri, id);

            try {
                int count = activity.getApplicationContext().getContentResolver().delete(uri, null, null);
                result = count == 1;
            } catch (Exception exception) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    RecoverableSecurityException recoverableSecurityException;
                    if (exception instanceof RecoverableSecurityException) {
                        recoverableSecurityException = (RecoverableSecurityException) exception;
                        IntentSender intentSender = recoverableSecurityException.getUserAction().getActionIntent().getIntentSender();
                        try {
                            activity.startIntentSenderForResult(intentSender, 111, null, 0, 0, 0, null);
                        } catch (IntentSender.SendIntentException e) {
                            e.printStackTrace();
                        }
                    } else {
//                        throw new RuntimeException(exception.getMessage(), exception);
                    }
                } else {
//                    throw new RuntimeException(exception.getMessage(), exception);
                }
            }

        } else {
            Cursor cursor2 = MediaStore.Images.Media.query(
                    resolver,
                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                    new String[]{MediaStore.Images.Media._ID},
                    MediaStore.Images.Media.DATA + "=?",
                    new String[]{imgPath},
                    null
            );
            if (cursor2.moveToFirst()) {
                long id = cursor2.getLong(0);
                Uri contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                uri = ContentUris.withAppendedId(contentUri, id);
                int count = activity.getApplicationContext().getContentResolver().delete(uri, null, null);
                result = count == 1;
            }
        }

        return result;
    }
}

