package com.cordova.camera;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.cordova.camera.util.FileUtil;
import com.cordova.camera.view.CameraActivity;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by xiang.wang on 2017/4/14.
 */

public class CameraPlugin extends CordovaPlugin {
  private static final String ACTION_TAKE_PICTURE = "takePicture";
  private static final int REQUEST_CODE_CAMERA = 102;
  private CallbackContext mCallbackContext;


  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    boolean isCorp = true;
    if(args != null && args.length() > 0){
      JSONObject object = args.optJSONObject(0);
      if(object != null){
        isCorp = object.optBoolean("isCorp");
      }
    }
    if(ACTION_TAKE_PICTURE.equals(action)){
      Intent intent = new Intent(cordova.getActivity(), CameraActivity.class);
      intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, FileUtil.getSaveFile(cordova.getActivity()).getAbsolutePath());
      intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
      intent.putExtra("isCrop", isCorp);
      cordova.startActivityForResult(CameraPlugin.this,intent, REQUEST_CODE_CAMERA);
    }
    mCallbackContext = callbackContext;
    return true;
  }


  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
      if (intent != null) {
        String path = FileUtil.getSaveFile(cordova.getActivity()).getAbsolutePath();
        if(mCallbackContext != null){
          if(!path.isEmpty()){
            mCallbackContext.success(path);
          }else{
            mCallbackContext.success("取消拍照");
          }
        }
      }
    }
  }
}
