package com.nimble.androidnative;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

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

import java.io.ByteArrayOutputStream;

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)) {
            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);
            this.callbackContext = callbackContext;
            Log.e("EditImagePlugin", "execute 109");
//            test();
            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";
                byte[] bytes = Base64.decode(data.getBytes(), Base64.DEFAULT);
                Bitmap newBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                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);
        }

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

    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");
            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 {
            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);
                this.callbackContext.success(js_out);
                Log.e("processPicture", js_out);
                js_out = null;
                output = null;
                code = null;
            }
        } catch (Exception e) {
        }
        jpeg_data = null;
    }
}
