package com.tencent.trtc;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;

import com.tencent.trtc.CordovaEventKit;
import com.tencent.trtc.event.Events;
import com.tencent.trtc.videocall.VideoCallingEnterActivity;
import com.tencent.trtc.videocall.VideoCallingActivity;

import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;


public class TrtcPlugin extends CordovaPlugin {
    private static final String TAG = TrtcPlugin.class.getSimpleName();

    /**
     * 加入会议
     * @param args
     * @param callbackContext
     * @throws JSONException
     */
    public void joinChannel(JSONArray args, CallbackContext callbackContext) throws JSONException {
        Intent intent = new Intent(this.cordova.getActivity(), VideoCallingActivity.class);
        JSONObject arg = args.getJSONObject(0);
        String ROOM_ID = arg.getString("ROOM_ID");
        String USER_ID = arg.getString("USER_ID");
        int SDK_APP_ID = arg.getInt("SDK_APP_ID");
        String USER_SIG = arg.getString("USER_SIG");
        intent.putExtra("room_id", ROOM_ID);
        intent.putExtra("user_id", USER_ID);
        intent.putExtra("sdk_app_id", SDK_APP_ID);
        intent.putExtra("user_sig", USER_SIG);
        cordova.startActivityForResult(this, intent, 666);
    }


    public void userInfoChange(JSONArray args,CallbackContext callbackContext) throws JSONException{
        JSONObject object = args.getJSONObject(0);
        if(object != null){
            Events.fireEvent("userinfo.update",extra -> {
                try {
                    extra.putString("userId",object.getString("userId"));
                    extra.putString("displayName",object.getString("displayName"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        cordova.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Method method = TrtcPlugin.class.getDeclaredMethod(action, JSONArray.class, CallbackContext.class);
                    method.invoke(TrtcPlugin.this, args, callbackContext);
                } catch (Exception e) {
                    Log.e(TAG, e.toString());
                }
            }
        });
        return true;
    }


    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        CordovaEventKit.init(this);
    }


}
