package com.sobot.utils;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: SD 工具类 适配了AndroidQ分区存储
 * @Author: znw
 * @Date: 2021/7/15 下午5:48
 * @Version: 1.0
 */
public class SobotSDCardUtils {

    private static String TAG = SobotSDCardUtils.class.getSimpleName();

    private static final String ROOT_DIR = "sobot";
    private static final String CACHE_DIR = "cache";

    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public static boolean isExitsSdcard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }

    /**
     * 获取存储位置
     *
     * @return
     */
    public static String getSDCardRootPath(Context context) {
        String path;
        if (isExitsSdcard()) {
            //SD卡已装入
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                //  /storage/emulated/0/sobot/com.sobot.chat.sdktest/cache/
                path = getRootDir(context) + File.separator;
            } else {
                //  /storage/emulated/0/Android/data/com.sobot.chat.sdktest/files/Download/cache/
                path = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + CACHE_DIR + File.separator;
            }
            Log.i(TAG, "SD卡已装入 存储路径：" + path);
        } else {
            //外部存储不可用
            path = context.getFilesDir().getPath() + File.separator + "sobot";
            Log.i(TAG, "外部存储不可用 存储路径：" + path);
        }
        return path;
    }

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

    /**
     * 获取私有目录
     *
     * @param context
     * @return
     */
    public static String getPrivatePath(Context context) {
        return context.getFilesDir().getPath();
    }

    /**
     * 如果url中有中文就把中文编译一次
     *
     * @param url
     * @return
     */
    public static String encode(String url) {
        if (url != null) {
            Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
            while (matcher.find()) {
                String tmp = matcher.group();
                try {
                    url = url.replaceAll(tmp, URLEncoder.encode(tmp, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return url;
    }
}