package com.sobot.widget.ui.utils;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.fragment.app.Fragment;
import androidx.core.content.FileProvider;

import com.sobot.utils.SobotIOUtils;
import com.sobot.widget.ui.SobotBaseConstant;
import com.sobot.widget.ui.toast.SobotToastUtil;

import java.io.File;
import java.security.MessageDigest;

public class SobotWidgetUtils {

    /**
     * activity打开选择图片界面
     *
     * @param act
     */
    public static void openSelectPic(Activity act) {
        openSelectPic(act, null);
    }

    /**
     * Fragment打开选择图片界面
     *
     * @param act
     */
    public static void openSelectPic(Activity act, Fragment childFragment) {
        if (act == null) {
            return;
        }
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        try {
            if (childFragment != null) {
                childFragment.startActivityForResult(intent, SobotBaseConstant.REQUEST_CODE_PICTURE);
            } else {
                act.startActivityForResult(intent, SobotBaseConstant.REQUEST_CODE_PICTURE);
            }
        } catch (Exception e) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            try {
                if (childFragment != null) {
                    childFragment.startActivityForResult(intent, SobotBaseConstant.REQUEST_CODE_PICTURE);
                } else {
                    act.startActivityForResult(intent, SobotBaseConstant.REQUEST_CODE_PICTURE);
                }
            } catch (Exception exception) {
                exception.printStackTrace();
                SobotToastUtil.showToast(act.getApplicationContext(), SobotResourceUtils.getResString(act, "sobot_not_open_album"));
            }
        }
    }

    /**
     * activity打开选择视频界面
     *
     * @param act
     */
    public static void openSelectVedio(Activity act) {
        openSelectVedio(act, null);
    }

    /**
     * Fragment打开选择视频界面
     *
     * @param act
     */
    public static void openSelectVedio(Activity act, Fragment childFragment) {
        if (act == null) {
            return;
        }
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("video/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
            intent.setDataAndType(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, "video/*");
        }
        try {
            if (childFragment != null) {
                childFragment.startActivityForResult(intent, SobotBaseConstant.REQUEST_CODE_VIDEO);
            } else {
                act.startActivityForResult(intent, SobotBaseConstant.REQUEST_CODE_VIDEO);
            }
        } catch (Exception e) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("video/*");
            try {
                if (childFragment != null) {
                    childFragment.startActivityForResult(intent, SobotBaseConstant.REQUEST_CODE_VIDEO);
                } else {
                    act.startActivityForResult(intent, SobotBaseConstant.REQUEST_CODE_VIDEO);
                }
            } catch (Exception exception) {
                exception.printStackTrace();
                SobotToastUtil.showToast(act.getApplicationContext(), SobotResourceUtils.getResString(act, "sobot_not_open_album"));
            }
        }
    }


    /**
     * activity打开相机
     *
     * @param act
     * @return
     */
    public static File openCamera(Activity act) {
        return openCamera(act, null);
    }

    /**
     * Fragment打开相机
     *
     * @param act
     * @param childFragment 打开相机的fragment
     * @return
     */
    public static File openCamera(Activity act, Fragment childFragment) {
        String path = getPicDir(act) + System.currentTimeMillis() + ".jpg";
        // 创建图片文件存放的位置
        File cameraFile = new File(path);
        SobotIOUtils.createFolder(cameraFile.getParentFile());
        Uri uri;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, cameraFile.getAbsolutePath());
                uri = act.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        contentValues);
            } else {
                uri = getUri(act, cameraFile);
            }

        } else {
            uri = Uri.fromFile(cameraFile);
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore
                .EXTRA_OUTPUT, uri);
//        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        if (childFragment != null) {
            childFragment.startActivityForResult(intent, SobotBaseConstant.REQUEST_CODE_MAKEPICTUREFROMCAMERA);
        } else {
            act.startActivityForResult(intent, SobotBaseConstant.REQUEST_CODE_MAKEPICTUREFROMCAMERA);
        }

        return cameraFile;
    }

    public static Uri getUri(Context context, File file) {
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context, context.getPackageName() + ".sobot_fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }

    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static final String PIC_DIR = "pic";
    private static String mRootPath;
    private static final String ROOT_DIR = "download";

    //sdcard/download/xxxx/pic
    public static String getPicDir(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            return getRootDir(context) + File.separator + PIC_DIR + File.separator;
        } else {
            return context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath() + File.separator;
        }

    }

    public static String getRootDir(Context context) {
        if (mRootPath == null) {
            String packageName = context != null ? context.getPackageName() : "";
            mRootPath = Environment.getExternalStorageDirectory().getPath() + File.separator + ROOT_DIR + File.separator + encode(packageName + "cache_sobot");
        }
        return mRootPath;
    }

    private static String encode(String str) {
        StringBuilder sb = new StringBuilder();

        try {
            MessageDigest instance = MessageDigest.getInstance("MD5");
            byte[] digest = instance.digest(str.getBytes());
            for (byte b : digest) {
                int num = b & 0xff;
                String hex = Integer.toHexString(num);
                if (hex.length() < 2) {
                    sb.append("0");
                }
                sb.append(hex);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return sb.toString();
    }
}