/**
 * 视频通话信息设置页面
 */
package com.videogo.ui.videotalk;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.EditText;


import com.ez.baselib.utils.LogUtil;
import com.ez.basertc.RTCConstant;
import com.ez.ertcengine.ERTCEngine;
import com.videogo.EzvizApplication;
import com.videogo.constant.IntentConsts;
import com.videogo.exception.BaseException;
import com.videogo.global.DemoConfig;
import com.videogo.global.GlobalKit;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.util.LocalInfo;
import com.videogo.widget.TitleBar;

import ezviz.ezopensdk.R;
import ezviz.ezopensdkcommon.common.EZPermissionUtil;
import ezviz.ezopensdkcommon.common.RootActivity;

public class EZJoinMeetingActivity extends RootActivity {

    // region --- 全局变量|global variable ---

    protected static final String TAG = EZJoinMeetingActivity.class.getSimpleName();

    private EditText appIdEt;
    private EditText ertcClientTokenEt;
    private EditText ertcDeviceTokenEt;
    private EditText roomIdEt;
    private EditText userIdEt;

    private EZCameraInfo mCameraInfo = null;

    private boolean isClientCallDevice;// true:客户端呼叫设备端 false:设备端呼叫，客户端接听

    // endregion

    // region --- 生命周期|Life Cycle ---

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join_meeting);
        initData();
        initView();
        if (GlobalKit.isJCTest) {
            appIdEt.setText(DemoConfig.ERTC_APP_ID);
            ertcClientTokenEt.setText(DemoConfig.ERTC_CLIENT_TOKEN);
            ertcDeviceTokenEt.setText(DemoConfig.ERTC_DEVICE_TOKEN);
            roomIdEt.setText(DemoConfig.ERTC_ROOM_ID);
            userIdEt.setText(DemoConfig.ERTC_USER_ID);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        EZPermissionUtil.onResume(this);
    }

    // endregion

    // region --- Click点击事件|Click event ---

    /**
     * 客户端发起视频通话
     */
    public void onClickVideoTalk(View view) {
        if (!checkVideoTalkParams()) {
            return;
        }
        isClientCallDevice = true;
        checkPermissions();
    }

    /**
     * 设备端端发起视频通话后，客户端接听
     * 设备端发起呼叫后，萤石webhook消息会把roomId推送给您的服务平台，客户端进入同一个roomId即可实现接听
     */
    public void onClickAnswerDeviceCall(View view) {
        if (!checkVideoTalkParams()) {
            return;
        }
        isClientCallDevice = false;
        checkPermissions();
    }

    /**
     * 设备端端发起视频通话后，客户端拒接
     */
    public void onClickRejectDeviceCall(View view) {
        if (!checkVideoTalkParams()) {
            return;
        }
        new Thread(() -> {
            try {
                boolean ret = EzvizApplication.getOpenSDK().rejectVideoCallReqFromDevice(appIdEt.getText().toString(), ertcDeviceTokenEt.getText().toString(),
                        roomIdEt.getText().toString(), mCameraInfo.getDeviceSerial(), mCameraInfo.getCameraNo(), userIdEt.getText().toString());
                if (ret) {
                    showToast("拒接成功");
                }
            } catch (BaseException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void onClickClearEditText(View view) {
        int id = view.getId();
        if (id == R.id.btn_appId_clear) {
            appIdEt.setText("");
        } else if (id == R.id.btn_ertc_client_token_clear) {
            ertcClientTokenEt.setText("");
        } else if (id == R.id.btn_ertc_device_token_clear) {
            ertcDeviceTokenEt.setText("");
        } else if (id == R.id.btn_roomId_clear) {
            roomIdEt.setText("");
        } else if (id == R.id.btn_userId_clear) {
            userIdEt.setText("");
        }
    }

    private boolean checkVideoTalkParams() {
        String appId = appIdEt.getText().toString();
        String ertcClientToken = ertcClientTokenEt.getText().toString();
        String ertcDeviceToken = ertcDeviceTokenEt.getText().toString();
        String roomId = roomIdEt.getText().toString();
        String userId = userIdEt.getText().toString();
        if (TextUtils.isEmpty(appId) || TextUtils.isEmpty(ertcClientToken) || TextUtils.isEmpty(ertcDeviceToken) || TextUtils.isEmpty(roomId) || TextUtils.isEmpty(userId)) {
            showToast("信息不能为空");
            return false;
        }
        return true;
    }

    // endregion

    // region --- ERTC初始化|ERTC initialization ---

    private void initErtcEngine() {
        String appId = appIdEt.getText().toString();
        String ertcClientToken = ertcClientTokenEt.getText().toString();
        String ertcDeviceToken = ertcDeviceTokenEt.getText().toString();
        String roomId = roomIdEt.getText().toString();
        String userId = userIdEt.getText().toString();
        ErtcHelper.initERTCEngine(EZJoinMeetingActivity.this, appId, new ERTCEngine.OnInitListener() {
            @Override
            public void onInitialization(ERTCEngine engine) {
                LogUtil.d(TAG, "Init OK");
                ErtcHelper.ertcEngine = engine;
//                ErtcHelper.ertcEngine.setERTCDebugAudioLog(true);

                RTCConstant.EnterParam localUserInfo = new RTCConstant.EnterParam();
                localUserInfo.roomId = roomId;
                localUserInfo.userId = userId;
                localUserInfo.token = ertcClientToken;
                localUserInfo.appId = appId;

                ErtcRoomActivity.launch(EZJoinMeetingActivity.this, localUserInfo, mCameraInfo, ertcDeviceToken,
                        isClientCallDevice,true, true);
            }

            @Override
            public void onError(int code) {
                LogUtil.d(TAG, "Init failed error:" + code);
            }
        });
    }

    // endregion

    // region --- init ---

    private void initData() {
        // 初始化mLocalInfo，记录屏幕尺寸信息
        LocalInfo mLocalInfo = LocalInfo.getInstance();
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        if (mLocalInfo != null) {
            mLocalInfo.setScreenWidthHeight(metric.widthPixels, metric.heightPixels);
            mLocalInfo.setNavigationBarHeight((int) Math.ceil(25 * getResources().getDisplayMetrics().density));
        }
        mCameraInfo = getIntent().getParcelableExtra(IntentConsts.EXTRA_CAMERA_INFO);
    }

    private void initView() {
        initTitleBar();

        appIdEt = findViewById(R.id.et_appId);
        ertcClientTokenEt = findViewById(R.id.et_ertc_client_token);
        ertcDeviceTokenEt = findViewById(R.id.et_ertc_device_token);
        roomIdEt = findViewById(R.id.et_roomId);
        userIdEt = findViewById(R.id.et_userId);
    }

    private void initTitleBar() {
        TitleBar mTitleBar = findViewById(R.id.title_bar);
        mTitleBar.addBackButton(view -> finish());
        mTitleBar.setTitle("视频通话");
    }

    // endregion

    // region --- 动态权限申请|Dynamic permission application ---

    public void checkPermissions() {
        EZPermissionUtil.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO},
                1000, () -> afterHasPermission());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EZPermissionUtil.handleResult(requestCode, permissions, grantResults);
    }

    private void afterHasPermission() {
        // 有相机、麦克风权限后，初始化ERTCEngine
        initErtcEngine();
    }

    // endregion

}