package uni.deepoil.com;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.util.ArrayList;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

/**
 * 权限插件
 *
 * @author Berial
 * @since 2025-06-12
 */
public class PermissionModule extends UniModule {

    @UniJSMethod
    public void requestImagePermissions(UniJSCallback callback) {
        ArrayList<String> list = new ArrayList<>();
        list.add(Permission.CAMERA);
        list.add(Permission.READ_MEDIA_VISUAL_USER_SELECTED);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            list.add(Permission.READ_MEDIA_IMAGES);
            list.add(Permission.READ_MEDIA_VIDEO);
            list.add(Permission.READ_MEDIA_AUDIO);
//        } else {
//            list.add(Permission.WRITE_EXTERNAL_STORAGE);
//            list.add(Permission.READ_EXTERNAL_STORAGE);
//        }

        try {
            Context context = mUniSDKInstance.getContext();
            if (XXPermissions.isGranted(context, list)) {
                callback.invoke(generateResult(true));
            } else {
                XXPermissions.with(context)
                        .permission(list)
                        .request((perms, allGranted) -> {
                            callback.invoke(generateResult(allGranted));
                        });
            }
        } catch (Exception e) {
            Log.e("PermissionModule", e.toString());
        }
    }

    @UniJSMethod
    public void requestPermissions(JSONObject options, UniJSCallback callback) {
        JSONArray array = options.getJSONArray("permissions");
        if (array != null) {
            ArrayList<String> list = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                String permission = array.getString(i);
                if (!TextUtils.isEmpty(permission)) {
                    list.add(permission);
                }
            }

            Context context = mUniSDKInstance.getContext();
            if (XXPermissions.isGranted(context, list)) {
                callback.invoke(generateResult(true));
            } else {
                XXPermissions.with(context)
                        .permission(list)
                        .request((perms, allGranted) -> {
                            callback.invoke(generateResult(allGranted));
                        });
            }
        } else {
            callback.invoke(generateResult(false));
        }
    }

    private JSONObject generateResult(boolean success) {
        JSONObject obj = new JSONObject();
        obj.put("success", success);
        return obj;
    }
}
