package com.zhaohaoting.framework.utils.file;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.zhaohaoting.framework.ZhtLibrary;
import com.zhaohaoting.framework.utils.ToastUtils;
import com.zhaohaoting.framework.utils.md5.MD5;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * author：Created by zhaohaoting on 2018/1/10 11:51
 * email：526309416@qq.com
 * desc：
 */

public class FileUtils {

    private static final int COLORDRAWABLE_DIMENSION = 2;
    private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;

    private static final int MAX_ORIGINAL_IMAGE_SIZE = 1280;
    private static final int COMPRESSED_SIZE = 100;


    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.CHINA);

    public static final String getParentPath() {
        return getPackageName();
    }
    public static final String getPackageName() {
        return ZhtLibrary.getContext().getPackageName();
    }

    public static final String getBaseDir() {
        return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + getPackageName();
    }
    /**
     * 生成相册的图片文件路径
     */
    public static String getPicDir() {
        return getBaseDir() + "/picture/";
    }

    /**
     * 生成的视频文件路径
     */
    public static String getVideoDir() {
        return getBaseDir() + "/video/";
    }

    /**
     * 生成的音乐文件路径
     */
    public static String getMusicDir() {
        return getBaseDir() + "/music/";
    }

    /**
     * 生成的缓存路径
     */
    public static String getCacheDir() {
        return getBaseDir() + "/cache/";
    }

    @NonNull
    public static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public static String getVideoPath(String fileNamePrefix) {
        long currentTime = System.currentTimeMillis();
        String time = sdf.format(new Date(currentTime));
        String tempOutputPath;
        File outputFile = ZhtLibrary.getContext().getExternalFilesDir(Environment.DIRECTORY_MOVIES);
        if (!outputFile.exists()) {
            boolean mkdirs = outputFile.mkdirs();
        }
        String outputPath = outputFile.getPath();
        if (TextUtils.isEmpty(fileNamePrefix)) {
            tempOutputPath = outputPath + "/" + time + ".mp4";
        } else {
            tempOutputPath = outputPath + "/" + fileNamePrefix + time + ".mp4";
        }
        return tempOutputPath;
    }

    public static boolean deleteFile(String path) {

        synchronized (FileUtils.class) {
            if (TextUtils.isEmpty(path)) {
                return true;
            }

            File file = new File(path);
            if (!file.exists()) {
                return true;
            }
            if (file.isFile()) {
                return file.delete();
            }
            if (!file.isDirectory()) {
                return false;
            }
            File[] filesList = file.listFiles();

            if (filesList != null) {
                for (File f : filesList) {
                    if (f.isFile()) {
                        f.delete();
                    } else if (f.isDirectory()) {
                        deleteFile(f.getAbsolutePath());
                    }
                }
            }

            return file.delete();
        }

    }


    /**
     * 直接保存到相册文件夹
     */
    public static File savePictureAlbum(Bitmap bitmap, String fileName) {
        File file = new File(getPicDir(), fileName);
        if (!file.exists()) {
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
        } else {
            file.delete();
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static File copyPicture(String originalPath, String fileName, String toPath) {
        File file = new File(toPath, fileName);
        File originalFile = new File(originalPath);
        if (toPath.equals(originalFile.getParent())) {
            return originalFile;
        }
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        if (!file.exists()) {
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
        } else {
            file.delete();
        }
        try {
            fileInputStream = new FileInputStream(originalFile);
            fileOutputStream = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(buf)) != -1) {
                fileOutputStream.write(buf, 0, len);
                fileOutputStream.flush();
            }
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 复制到相册文件夹
     */
    public static File copyPictureAlbum(String originalPath, String fileName) {
        return copyPicture(originalPath, fileName, getPicDir());
    }

    public static File isHaveFilePic(String fileName) {
        File file = new File(getPicDir(), fileName);
        if (file.exists()) {
            return file;
        } else {
            return null;
        }
    }

    /**
     * 图片压缩
     */
    public static File compressImageBitmap(String photoPath) {
        File file = null;
        Bitmap bitmap = null;
        try {
            bitmap = compressImageBitmap(photoPath, MAX_ORIGINAL_IMAGE_SIZE, MAX_ORIGINAL_IMAGE_SIZE);
            if (bitmap != null) {
                String dir = ZhtLibrary.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/thumbnail/";
                file = new File(dir, MD5.getStreamMD5(photoPath) + ".jpg");
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {
                    boolean mkdirs = parentFile.mkdirs();
                }
                if (!file.exists()) {
                    boolean newFile = file.createNewFile();
                    BufferedOutputStream bos = null;
                    try {
                        bos = new BufferedOutputStream(new FileOutputStream(file));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSED_SIZE, bos);
                        bos.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    if (!bitmap.isRecycled()) {
                        bitmap.recycle();
                    }
                }
            }
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 图片压缩
     */
    public static Bitmap compressImageBitmap(String photoPath, int ivWidth, int ivHeight) throws IOException {

        //根据图片路径，获取bitmap的宽和高
        ExifInterface exifInterface = new ExifInterface(photoPath);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(photoPath, options);

        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
        int photoWidth;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_90 || orientation == ExifInterface.ORIENTATION_ROTATE_270 || orientation == ExifInterface.ORIENTATION_TRANSPOSE || orientation == ExifInterface.ORIENTATION_TRANSVERSE) {
            photoWidth = ivWidth;
            ivWidth = ivHeight;
            ivHeight = photoWidth;
        }
        photoWidth = options.outWidth;
        int photoHeight = options.outHeight;
        //获取缩放比例
        int inSampleSize = 1;
        if (photoWidth > ivWidth || photoHeight > ivHeight) {
            int widthRatio = Math.round((float) photoWidth / ivWidth);
            int heightRatio = Math.round((float) photoHeight / ivHeight);
            inSampleSize = Math.max(widthRatio, heightRatio);
        }
        //使用现在的options获取Bitmap
        options.inSampleSize = inSampleSize;
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
        if (bitmap == null) return null;
        Matrix matrix = new Matrix();
        switch (orientation) {
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                matrix.preScale(-1.0F, 1.0F);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.setRotate(180.0F, (float) photoWidth / 2.0F, (float) photoHeight / 2.0F);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                matrix.preScale(1.0F, -1.0F);
                break;
            case ExifInterface.ORIENTATION_TRANSPOSE:
                matrix.setRotate(90.0F, (float) photoWidth / 2.0F, (float) photoHeight / 2.0F);
                matrix.preScale(1.0F, -1.0F);
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.setRotate(90.0F, (float) photoWidth / 2.0F, (float) photoHeight / 2.0F);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                matrix.setRotate(270.0F, (float) photoWidth / 2.0F, (float) photoHeight / 2.0F);
                matrix.preScale(1.0F, -1.0F);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.setRotate(270.0F, (float) photoWidth / 2.0F, (float) photoHeight / 2.0F);
        }

        float xS = (float) ivWidth / (float) bitmap.getWidth();
        float yS = (float) ivHeight / (float) bitmap.getHeight();
        matrix.postScale(Math.min(xS, yS), Math.min(xS, yS));
        try {
            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError var21) {
            return null;
        }
    }

    /**
     * 自定义图片名，获取照片的file
     */
    public static File createImgFile(String name) {
        //创建文件
        String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date()) + name + ".jpg";//确定文件名
        File dir = ZhtLibrary.getContext().getFilesDir();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = ZhtLibrary.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        File tempFile = new File(dir, fileName);
        try {
            if (tempFile.exists()) {
                tempFile.delete();
            }
            tempFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取文件路径
//        photoPath = tempFile.getAbsolutePath();
        return tempFile;
    }

    public static File saveImageToGallery(Bitmap bmp, String fileName) {
        // 首先保存图片
        File dir = ZhtLibrary.getContext().getFilesDir();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = ZhtLibrary.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        File file = new File(dir, fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static File saveImageToGalleryAllPath(Bitmap bmp, String dir) {
        // 首先保存图片
        File file = new File(dir);
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static String getCanchePath() {
        File dir = ZhtLibrary.getContext().getFilesDir();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = ZhtLibrary.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        return dir.getAbsolutePath();
    }

    /**
     * 从本地s读图片
     */
    public static Bitmap getBitmapFromLocal(String url) {
        try {
            File file = new File(url);
            if (file.exists()) {
                Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
                return bitmap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap getBitmapFromDrawable(Drawable drawable) {
        if (drawable == null) {
            return null;
        }

        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        try {
            Bitmap bitmap;

            if (drawable instanceof ColorDrawable) {
                bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
            } else {
                bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
            }

            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return bitmap;
        } catch (OutOfMemoryError e) {
            return null;
        }
    }

    public static File isHaveFile(String fileName) {
        File file = new File(getCanchePath(), fileName);
        if (file.exists()) {
            return file;
        }
        return null;
    }

    //把文件插入到系统图库

    /**
     * @param context
     * @param targetFile 要保存的照片文件
     * @param path       要保存的照片的路径地址
     */
    public static void addMediaStore(Context context, File targetFile, String path) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues newValues = new ContentValues(5);
        newValues.put(MediaStore.Images.Media.DISPLAY_NAME, targetFile.getName());
        newValues.put(MediaStore.Images.Media.DATA, targetFile.getPath());
        newValues.put(MediaStore.Images.Media.DATE_MODIFIED, System.currentTimeMillis() / 1000);
        newValues.put(MediaStore.Images.Media.SIZE, targetFile.length());
        newValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, newValues);
        MediaScannerConnection.scanFile(context, new String[]{path}, null, null);//刷新相册
    }

    //针对非系统影音资源文件夹
    public static void insertIntoMediaStore(Context context, boolean isVideo, File saveFile, long createTime) {
        ContentResolver mContentResolver = context.getContentResolver();
        if (createTime == 0)
            createTime = System.currentTimeMillis();
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.TITLE, saveFile.getName());
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, saveFile.getName());
        //值一样，但是还是用常量区分对待
        values.put(isVideo ? MediaStore.Video.VideoColumns.DATE_TAKEN
                : MediaStore.Images.ImageColumns.DATE_TAKEN, createTime);
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, System.currentTimeMillis());
        values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis());
        if (!isVideo)
            values.put(MediaStore.Images.ImageColumns.ORIENTATION, 0);
        values.put(MediaStore.MediaColumns.DATA, saveFile.getAbsolutePath());
        values.put(MediaStore.MediaColumns.SIZE, saveFile.length());
        values.put(MediaStore.MediaColumns.MIME_TYPE, isVideo ? getVideoMimeType(saveFile.getAbsolutePath()) : "image/jpeg");
        //插入
        mContentResolver.insert(isVideo
                ? MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                : MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        scanFile(context, saveFile.getAbsolutePath());
    }

    // 获取video的mine_type,暂时只支持mp4,3gp
    private static String getVideoMimeType(String path) {
        String lowerPath = path.toLowerCase();
        if (lowerPath.endsWith("mp4") || lowerPath.endsWith("mpeg4")) {
            return "video/mp4";
        } else if (lowerPath.endsWith("3gp")) {
            return "video/3gp";
        }
        return "video/mp4";
    }

    /**
     * 针对系统文夹只需要扫描,不用插入内容提供者,不然会重复
     *
     * @param context  上下文
     * @param filePath 文件路径
     */
    private static void scanFile(Context context, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) return;
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(new File(filePath)));
        context.sendBroadcast(intent);
        ToastUtils.show("成功保存到相册");
    }
}
