/**
 * An Image Picker Plugin for Cordova/PhoneGap.
 */
package com.synconset;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;

import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;

// import android.support.v4.app.ActivityCompat;
// import android.support.v4.content.ContextCompat;
// 更改了权限请求接口
// import androidx.core.app.ActivityCompat;
// import androidx.core.content.ContextCompat;

public class ImagePicker extends CordovaPlugin {

    private static final String ACTION_GET_PICTURES = "getPictures";
    private static final String ACTION_HAS_READ_PERMISSION = "hasReadPermission";
    private static final String ACTION_REQUEST_READ_PERMISSION = "requestReadPermission";

    private static final int PERMISSION_REQUEST_CODE = 100;

    private CallbackContext callbackContext;
    // image options
    private JSONObject params;

    public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
        if (cordova == null) return false;

        this.callbackContext = callbackContext;

        if (ACTION_HAS_READ_PERMISSION.equals(action)) {
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, hasReadPermission()));

        } else if (ACTION_REQUEST_READ_PERMISSION.equals(action)) {
            requestReadPermission();

        } else if (ACTION_GET_PICTURES.equals(action)) {
            params = args.getJSONObject(0);

            if (hasReadPermission()) {
                getPictures();
            } else {
                cordovaRequestPermission();
            }

        } else {
            return false;
        }
        return true;
    }

    @SuppressLint("InlinedApi")
    private boolean hasReadPermission() {
        return Build.VERSION.SDK_INT < 23 || cordova.hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    @SuppressLint("InlinedApi")
    private void requestReadPermission() {
        if (!hasReadPermission()) {
            cordovaRequestPermission();
        } else {
            callbackContext.success();
        }
    }

    private void cordovaRequestPermission() {
        cordova.requestPermission(this, PERMISSION_REQUEST_CODE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    private void getPictures() throws JSONException  {
        final Intent imagePickerIntent = new Intent(cordova.getActivity(), MultiImageChooserActivity.class);
        int max = 20;
        int desiredWidth = 0;
        int desiredHeight = 0;
        int quality = 100;
        int outputType = 0;
        if (params.has("maximumImagesCount")) {
            max = params.getInt("maximumImagesCount");
        }
        if (params.has("width")) {
            desiredWidth = params.getInt("width");
        }
        if (params.has("height")) {
            desiredHeight = params.getInt("height");
        }
        if (params.has("quality")) {
            quality = params.getInt("quality");
        }
        if (params.has("outputType")) {
            outputType = params.getInt("outputType");
        }

        imagePickerIntent.putExtra("MAX_IMAGES", max);
        imagePickerIntent.putExtra("WIDTH", desiredWidth);
        imagePickerIntent.putExtra("HEIGHT", desiredHeight);
        imagePickerIntent.putExtra("QUALITY", quality);
        imagePickerIntent.putExtra("OUTPUT_TYPE", outputType);

        cordova.startActivityForResult(this, imagePickerIntent, 0);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        params = null;

        if (resultCode == Activity.RESULT_OK && data != null) {
            int sync = data.getIntExtra("bigdata:synccode", -1);
            final Bundle bigData = ResultIPC.get().getLargeData(sync);
      
            ArrayList<String> fileNames = bigData.getStringArrayList("MULTIPLEFILENAMES");
    
            JSONArray res = new JSONArray(fileNames);
            callbackContext.success(res);

        } else if (resultCode == Activity.RESULT_CANCELED && data != null) {
            String error = data.getStringExtra("ERRORMESSAGE");
            callbackContext.error(error);

        } else if (resultCode == Activity.RESULT_CANCELED) {
            JSONArray res = new JSONArray();
            callbackContext.success(res);

        } else {
            callbackContext.error("No images selected");
        }
    }

    /**
     * Choosing a picture launches another Activity, so we need to implement the
     * save/restore APIs to handle the case where the CordovaActivity is killed by the OS
     * before we get the launched Activity's result.
     *
     * @see "http://cordova.apache.org/docs/en/dev/guide/platforms/android/plugin.html#launching-other-activities"
     */
    public void onRestoreStateForActivityResult(Bundle state, CallbackContext callbackContext) {
        this.callbackContext = callbackContext;
    }

    @Override
    public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException {
        // For now we just have one permission, so things can be kept simple...
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (params != null) {
                getPictures();
            } else {
                callbackContext.success();
            }
        } else {
            // Tell the JS layer that something went wrong...
            callbackContext.error("Permission denied");
        }
    }

}
