package cn.shuto.plugin.capture;

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

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

import com.mabeijianxi.smallvideorecord2.DeviceUtils;
import com.mabeijianxi.smallvideorecord2.JianXiCamera;
import com.mabeijianxi.smallvideorecord2.MediaRecorderActivity;
import com.mabeijianxi.smallvideorecord2.model.MediaRecorderConfig;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;
import android.content.Intent;
import android.os.Bundle;
import org.apache.cordova.PermissionHelper;

import java.io.File;

/**
 * This class echoes a string called from JavaScript.
 */
public class CaptureCordovaPlugin extends CordovaPlugin {
    public static final int REQUEST_CODE = 0x777578;
    private final int PERMISSION_REQUEST_CODE = 0x001;
    private static String LOG_TAG = "CAPTURE_PLUGIN";
    private CallbackContext callbackContext;
    private JSONObject param;
    private String [] permissions = {
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    @Override
    protected void pluginInitialize() {
        // 设置拍摄视频缓存路径
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        if (DeviceUtils.isZte()) {
            if (dcim.exists()) {
                JianXiCamera.setVideoCachePath(dcim + "/capture/");
            } else {
                JianXiCamera.setVideoCachePath(dcim.getPath().replace("/sdcard/",
                        "/sdcard-ext/")
                        + "/capture/");
            }
        } else {
            JianXiCamera.setVideoCachePath(dcim + "/capture/");
        }
        // 初始化拍摄
        JianXiCamera.initialize(false, null);
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        this.callbackContext = callbackContext;
        this.param = args.optJSONObject(0);
        if (action.equals("capture")) {
            if(!hasPermisssion()) {
                requestPermissions(PERMISSION_REQUEST_CODE);
            } else {
                this.capture();
            }
            return true;
        }
        return false;
    }

    private void capture() {
        JSONObject obj = this.param;
        if (obj == null) {
            obj = new JSONObject();
        }
        boolean fullScreen = obj.optBoolean("needFull", true);
        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                .fullScreen(fullScreen)
                .smallVideoWidth(fullScreen?0:obj.optInt("width", 640))
                .smallVideoHeight(obj.optInt("height", 480))
                .recordTimeMax(obj.optInt("maxTime", 15000))
                .recordTimeMin(obj.optInt("minTime", 3000))
                .maxFrameRate(obj.optInt("maxFramerate", 24))
                .videoBitrate(obj.optInt("bitrate", 580000))
                .captureThumbnailsTime(obj.optInt("thumbnailsTime", 1))
                .build();
        Intent intentCapture = new Intent(this.cordova.getActivity().getBaseContext(), MediaRecorderActivity.class);
        // intentCapture.putExtra(OVER_ACTIVITY_NAME, overGOActivityName);
        intentCapture.putExtra(MediaRecorderActivity.MEDIA_RECORDER_CONFIG_KEY, config);
        intentCapture.setPackage(this.cordova.getActivity().getApplicationContext().getPackageName());
        this.cordova.startActivityForResult(this, intentCapture, REQUEST_CODE);
    }

    /**
     * Called when the barcode scanner intent completes.
     *
     * @param requestCode The request code originally supplied to startActivityForResult(),
     *                       allowing you to identify who this result came from.
     * @param resultCode  The integer result code returned by the child activity through its setResult().
     * @param intent      An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == REQUEST_CODE && this.callbackContext != null && intent != null) {
            Bundle bundle = intent.getExtras();
            JSONObject obj = new JSONObject();
            super.onActivityResult(requestCode, resultCode, intent);
            if(resultCode == Activity.RESULT_OK){
                try {
                    obj.put("directory", bundle.getString(MediaRecorderActivity.OUTPUT_DIRECTORY));
                    obj.put("video", bundle.getString(MediaRecorderActivity.VIDEO_URI));
                    obj.put("thumbnail", bundle.getString(MediaRecorderActivity.VIDEO_SCREENSHOT));
                    obj.put("cancelled", false);
                } catch (JSONException e) {
                    Log.d(LOG_TAG, "This should never happen");
                }
                callbackContext.success(obj);
            }else if (resultCode == Activity.RESULT_CANCELED){
                try {
                    obj.put("directory", "");
                    obj.put("video", "");
                    obj.put("thumbnail", "");
                    obj.put("cancelled", true);
                } catch (JSONException e) {
                    Log.d(LOG_TAG, "This should never happen");
                }
                callbackContext.error(obj);
            }
            else {
              this.callbackContext.error("Unexpected error");
            }
        }
    }

    /**
     * check application's permissions
     */
    public boolean hasPermisssion() {
        for(String p : permissions) {
            if(!PermissionHelper.hasPermission(this, p)) {
                return false;
            }
        }
        return true;
    }

    /**
     * We override this so that we can access the permissions variable, which no longer exists in
     * the parent class, since we can't initialize it reliably in the constructor!
     *
     * @param requestCode The code to get request action
     */
    public void requestPermissions(int requestCode) {
        PermissionHelper.requestPermissions(this, requestCode, permissions);
    }

   /**
   * processes the result of permission request
   *
   * @param requestCode The code to get request action
   * @param permissions The collection of permissions
   * @param grantResults The result of grant
   */
    public void onRequestPermissionResult(int requestCode, String[] permissions,
                                         int[] grantResults) throws JSONException {
        PluginResult result;
        for (int r : grantResults) {
            if (r == PackageManager.PERMISSION_DENIED) {
                Log.d(LOG_TAG, "Permission Denied!");
                result = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION);
                this.callbackContext.sendPluginResult(result);
                return;
            }
        }

        if (requestCode == PERMISSION_REQUEST_CODE) {
            this.capture();
        }
    }

    /**
     * This plugin launches an external Activity when the camera is opened, so we
     * need to implement the save/restore API in case the Activity gets killed
     * by the OS while it's in the background.
     */
    public void onRestoreStateForActivityResult(Bundle state, CallbackContext callbackContext) {
        this.callbackContext = callbackContext;
    }

}
