package com.jmricardo.plugin;

import android.Manifest;

import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.annotation.Permission;
import com.getcapacitor.annotation.PermissionCallback;

import org.json.JSONException;

import java.util.List;

@CapacitorPlugin(name = "AudioPermissions",
        permissions = {
                @Permission(strings = { Manifest.permission.RECORD_AUDIO }, alias = AudioPermissionsPlugin.AUDIO),
        })
public class AudioPermissionsPlugin extends Plugin {

    // Permission alias constants
    static final String AUDIO = "audio";

    private AudioPermissions implementation = new AudioPermissions();

    @Override
    @PluginMethod
    public void requestPermissions(PluginCall call) {
        // If the camera permission is defined in the manifest, then we have to prompt the user
        // or else we will get a security exception when trying to present the camera. If, however,
        // it is not defined in the manifest then we don't need to prompt and it will just work.
        if (isPermissionDeclared(AUDIO)) {
            // just request normally
            super.requestPermissions(call);
        } else {
            // the manifest does not define camera permissions, so we need to decide what to do
            // first, extract the permissions being requested
            JSArray providedPerms = call.getArray("permissions");
            List<String> permsList = null;
            try {
                permsList = providedPerms.toList();
            } catch (JSONException e) {}

            if (permsList != null && permsList.size() == 1 && permsList.contains(AUDIO)) {
                // the only thing being asked for was the camera so we can just return the current state
                checkPermissions(call);
            }
        }
    }
}
