package com.easemob.veckit.ui.widget.utils;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import androidx.core.content.ContextCompat;

import com.hyphenate.chat.GetRealFilePathFromUri;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FileSaveUtil {
    private final static String TAG = "FileSaveUtil";
    /**
     * 保存文本到公共目录(txt文本,其他文件同理)
     * 29 以下，需要提前申请文件读写权限
     * 29及29以上的，不需要权限
     * 保存的文件在 Download 目录下 huanxin文件夹内
     */
    public static void saveTextFile(Context context, String fileName, String fileType, String readPath) {
        if (TextUtils.isEmpty(readPath))
            return;
        if (Build.VERSION.SDK_INT < 29) {
            if (!isGranted(context)) {
                EMLog.e(TAG, "save to file need storage permission");
                return;
            }
            File destFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            if (!destFile.exists()){
                destFile.mkdirs();
            }

            File destPath = new File(destFile, fileName);
            save(destPath, readPath);
        } else {//android Q
            Uri contentUri;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                contentUri = MediaStore.Downloads.EXTERNAL_CONTENT_URI;
            } else
                contentUri = MediaStore.Downloads.INTERNAL_CONTENT_URI;

            //创建ContentValues对象，准备插入数据
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Downloads.MIME_TYPE, fileType);//文件格式 "text/plain"
            contentValues.put(MediaStore.Downloads.DATE_TAKEN, System.currentTimeMillis());
            contentValues.put(MediaStore.Downloads.DISPLAY_NAME, fileName);//文件名字
            Uri fileUri = context.getContentResolver().insert(contentUri, contentValues);
            if (fileUri == null)
                return;

            try (OutputStream outputStream = context.getContentResolver().openOutputStream(fileUri)) {
                if (outputStream != null) {
                    save(outputStream, readPath);
                }
            } catch (Exception e) {
                e.printStackTrace();
                context.getContentResolver().delete(fileUri, null, null);  // 失败的时候，删除此 uri 记录
            }
            // ignore
        }
    }

    private static void save(File saveFile, String path) {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        if (saveFile.exists()){
            saveFile.delete();
        }
        try {
            inputStream = new FileInputStream(path);
            outputStream = new FileOutputStream(saveFile);
            int len = 0;
            byte[] data = new byte[1024];
            while ((len = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private static void save(OutputStream outputStream, String path) {
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(path);
            int len = 0;
            byte[] data = new byte[1024];
            while ((len = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private static boolean isGranted(Context context) {
        return (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE));
    }
}
