package com.tencent.trtc;

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

public class CordovaEventKit {
    public static CordovaEventKit kit = null;
    private CordovaPlugin plugin;


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

    public static void init(CordovaPlugin plugin){
        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){
        if (plugin == null  || event == null || obj == null) {
            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() {
                plugin.webView.loadUrl("javascript:" + js);
            }
        });
    }
}
