package com.nimble.androidnative;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;

import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

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

import java.io.ByteArrayOutputStream;
import java.util.List;

import me.kareluo.imaging.IMGEditActivity;

public class EditImagePlugin extends CordovaPlugin {
    private int destType, showEdit = 1;
    private String data, markString;
    private int QUEST_CODE_EDIT = 1024;
    private static final int DATA_URL = 0;              // Return base64 encoded string
    private static final int FILE_URI = 1;              // Return file uri (content://media/external/images/media/2 for Android)
    private static final int NATIVE_URI = 2;
    public CallbackContext callbackContext;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if ("showImageEditTool".equals(action)) {
//            String da = Environment.getExternalStorageDirectory().getAbsolutePath() + "/images/20190418_114205.jpg";
//            Log.e("test", da);

//            Log.e("EditImagePlugin", "execute 100");
            this.destType = args.getInt(0);
//            Log.e("EditImagePlugin", "execute 101");
            this.data = args.getString(1);
            this.markString = args.getString(2);
            this.showEdit = args.getInt(3);
//            Log.e("array",args.toString());
            this.callbackContext = callbackContext;
//            Log.e("EditImagePlugin", "execute 109");
//            test();

            Acp.getInstance(cordova.getActivity()).request(new AcpOptions.Builder()
                            .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .build(),
                    new AcpListener() {
                        @SuppressLint("MissingPermission")
                        @Override
                        public void onGranted() {
                            startEdit();
                        }

                        @Override
                        public void onDenied(List<String> permissions) {

                        }
                    });
        }
        return true;
//        return super.execute(action, args, callbackContext);
    }

    public void startEdit() {
        Intent it = new Intent(cordova.getActivity(), IMGEditActivity.class);
        if (destType == FILE_URI || destType == NATIVE_URI) {
            it.putExtra("imageUrl", data);
        } else if (destType == DATA_URL) {
            String newPath = Utils.getAppDataDir() + "/" + System.currentTimeMillis() + ".jpg";
//            Log.e("base64", data);
            byte[] bytes = Base64.decode(data.getBytes(), Base64.DEFAULT);
//            Log.e("bytes", bytes.length + "");
            Bitmap newBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//            if (newBitmap == null) {
//                Log.e("newBitmap", "newBitmap is null");
//            }
            Utils.saveImage(newBitmap, newPath);
            it.putExtra("imageUrl", newPath);
        }
        it.putExtra("destType", destType);
        it.putExtra("markString", markString);
        if (showEdit == 1) {
            it.putExtra("enableEdit", true);
        } else if (showEdit == 0) {
            it.putExtra("enableEdit", false);
        }
        cordova.startActivityForResult(this, it, QUEST_CODE_EDIT);
        PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
        r.setKeepCallback(true);
        callbackContext.sendPluginResult(r);
    }

    public void test() {
//        Log.e("EditImagePlugin", "execute 2");
        destType = FILE_URI;
        data = Environment.getExternalStorageDirectory().getAbsolutePath() + "/images/20190418_114205.jpg";
//        Log.e("test", data);
        Bitmap bitmap = BitmapFactory.decodeFile(data);
//        if (bitmap == null) {
//            Log.e("test", "bitmap is null");
//        }
        String base64 = Utils.bitmapToBase64(bitmap);
        byte[] bytes = Base64.decode(base64.getBytes(), Base64.DEFAULT);
//        Log.e("base64", base64);
//        Log.e("EditImagePlugin", "execute 3");
        Bitmap newBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        String newPath = Utils.getAppDataDir() + "/" + System.currentTimeMillis() + ".jpg";
//        Log.e("test", newPath);
//        if (newBitmap == null) {
//            Log.e("test", "newBitmap is null");
//        }
        Utils.saveImage(newBitmap, newPath);
//        Log.e("EditImagePlugin", "execute 4");
        Intent it = new Intent(cordova.getActivity(), IMGEditActivity.class);
        if (destType == FILE_URI || destType == NATIVE_URI) {
            it.putExtra("imageUrl", data);
        } else if (destType == DATA_URL) {
            it.putExtra("imageUrl", newPath);
        }
        it.putExtra("destType", destType);
        it.putExtra("markString", markString);
        if (showEdit == 1) {
            it.putExtra("enableEdit", true);
        } else if (showEdit == 0) {
            it.putExtra("enableEdit", false);
        }
        cordova.startActivityForResult(this, it, QUEST_CODE_EDIT);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//        Log.e("requestCode", requestCode + "");
//        Log.e("onActivityResult", "1");
        if (requestCode == QUEST_CODE_EDIT) {
//            Log.e("onActivityResult", "2");
            if (intent != null) {
                String path = intent.getStringExtra("path");
                processResultFromCamera(destType, path);
            }
        }
        super.onActivityResult(requestCode, resultCode, intent);
    }

    private void processResultFromCamera(int destType, String imagePath) {
        if (destType == DATA_URL) {
            //base64
//            Log.e("onActivityResult", "3");
            processPicture(BitmapFactory.decodeFile(imagePath));
        } else if (destType == FILE_URI || destType == NATIVE_URI) {
            //path
//            Log.e("onActivityResult", "4");
            callbackContext.success(imagePath);
        }
    }

    public void processPicture(Bitmap bitmap) {
        ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
//        Bitmap.CompressFormat compressFormat = encodingType == JPEG ?
//                Bitmap.CompressFormat.JPEG :
//                Bitmap.CompressFormat.PNG;
        try {
//            Log.e("onActivityResult", "5");
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, jpeg_data)) {
                byte[] code = jpeg_data.toByteArray();
                byte[] output = Base64.encode(code, Base64.NO_WRAP);
                String js_out = new String(output);
//                Log.e("onActivityResult", "8");
                this.callbackContext.success(js_out);
//                Log.e("processPicture", js_out);
                js_out = null;
                output = null;
                code = null;
            }
        } catch (Exception e) {
        }
        jpeg_data = null;
    }
}
