package com.tencent.trtc;

import android.util.Log;

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

public class CordovaEventKit {
    public static CordovaEventKit kit = null;
    private static final String TAG = "CordovaEventKit";
    private CordovaPlugin plugin;


    private CordovaEventKit(CordovaPlugin plugin) {
        this.plugin = plugin;
    }

    public static void init(CordovaPlugin plugin){
        Log.d(TAG, "init");
        if(CordovaEventKit.kit == null){
            CordovaEventKit.kit = new CordovaEventKit(plugin);
        }
    }


    public void fireEvent(String event, JSONArray obj){
        this.fireEvent(event,obj == null ? null : obj.toString());
    }

    public void fireEvent(String event, JSONObject obj){
        this.fireEvent(event,obj == null ? null :obj.toString());
    }

    public void fireEvent(String event, String obj){
        Log.d(TAG,"fireEvent --- event:"+event+",obj:"+obj);
        if (plugin == null  || event == null || obj == null) {
            Log.w(TAG,"fireEvent --- plugin:"+plugin);
            return;
        }
        event = event.replace('\'','_');
        String format = "window.cordova.plugin.trtc.fireEvent('%s',%s);";
        final String js = String.format(format,event, obj);
        plugin.cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG,"fireEvent --- code:"+js);
                plugin.webView.loadUrl("javascript:" + js);
            }
        });
    }
}
