package com.simple.plugin.signDemo;

import android.content.Intent;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.simple.plugin.utilTwo.FileUtil;
import com.simple.plugin.utilTwo.JsonUtil;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class SigRe extends CordovaPlugin {
    private CallbackContext copy;
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        copy=callbackContext;
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        String jsonString = args.length() > 0 ? args.get(0).toString() : null;
        if (action.equals("sign")){
            String screenNum = JsonUtil.getJsonString(jsonString, "screenNum");
            if (TextUtils.isEmpty(screenNum)){
                screenNum="0";
            }
            String imgPath = JsonUtil.getJsonString(jsonString, "imgPath");
            if (TextUtils.isEmpty(imgPath)){
                imgPath="0";
            }
            cordova.getActivity().startActivity(new Intent(cordova.getActivity(),MainTwoActivity.class).putExtra("screenNum",screenNum).putExtra("imgPath",imgPath));
        }
        return true;
    }
    @Subscribe
    public void onEvent(EventImgPath imgPath){
        if (copy==null){
            return;
        }
        String fileImg=imgPath.getImagePath();
        imgPath.setImagePath(FileUtil.localToCdvFile(webView,fileImg));
        PluginResult pluginResult = null;
        try {
            Gson gson=new Gson();
            pluginResult = new PluginResult(PluginResult.Status.OK,new JSONObject(gson.toJson(imgPath)));
            pluginResult.setKeepCallback(true);
            copy.sendPluginResult(pluginResult);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
