package com.tongyi.videochatdemo;

import android.Manifest.permission;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.tongyi.video_chat_sdk.Constant;
import com.tongyi.video_chat_sdk.Constant.TYVoiceChatMode;
import com.tongyi.video_chat_sdk.data.request.TYDialogConfig;
import com.tongyi.video_chat_sdk.data.response.TYAvatarInitData;
import com.tongyi.video_chat_sdk.util.DeviceUtil;

/**
 * @author haojiahe
 * @date 2024/11/26
 * description:
 */
public class NativeChatConfigActivity extends AppCompatActivity {
    private static final String TAG = NativeChatConfigActivity.class.getSimpleName();
    private static final int PERMISSION_REQUEST_CODE = 100;
    private EditText etRtcInitConfig;
    private TYAvatarInitData tyAvatarInitData;
    private TYDialogConfig tyDialogConfig;
    private String mMode = TYVoiceChatMode.TAP2TALK;
    private boolean mKeepAlive = true;
    private boolean mKeepHistoryRecord;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DeviceUtil.setStatusBarColor(this);
        setContentView(R.layout.activity_native_chat_config);
        initView();
        checkPermission();
    }

    private void initView() {
        etRtcInitConfig = findViewById(R.id.et_rtc_init_config);

        // RTC入会信息示例
        String initData = "{\n" +
                "    \"sessionId\": \"8D64A228-2FF8-4A53-99F8-DE542F6BD034\",\n" +
                "    \"rtcParams\": {\n" +
                "      \"clientUserId\": \"client-7724949046319413\",\n" +
                "      \"gslb\": \"https://gw.rtn.aliyuncs.com\",\n" +
                "      \"appId\": \"9d7790d3-d14c-4b3b-a715-3531a4988827\",\n" +
                "      \"avatarUserId\": \"avatar-6581805399883749\",\n" +
                "      \"channel\": \"9050484675579200\",\n" +
                "      \"nonce\": \"\",\n" +
                "      \"serverUserId\": \"system-9268853200574999\",\n" +
                "      \"timestamp\": 1757411380,\n" +
                "      \"token\": \"b308fb1e1e72c392321c0524dd32fe0494e5ae958b9138d4fbdd09940baf737a\"\n" +
                "    }\n" +
                "  }";
        // etRtcInitConfig.setText(initData);


        findViewById(R.id.btStartChat).setOnClickListener(view -> verifyInput());

        RadioGroup rbChatType = findViewById(R.id.rbChatType);
        rbChatType.setOnCheckedChangeListener((group, checkedId) -> {
            // 根据 checkedId 获取被选中的 RadioButton
            if (checkedId == R.id.rb_push2talk) {
                mMode = TYVoiceChatMode.PUSH2TALK;
            } else if (checkedId == R.id.rb_tap2talk) {
                mMode = TYVoiceChatMode.TAP2TALK;
            } else if (checkedId == R.id.rb_duplex) {
                mMode = TYVoiceChatMode.DUPLEX;
            }
        });

        RadioGroup rgKeepAlive = findViewById(R.id.rg_keep_alive);
        rgKeepAlive.setOnCheckedChangeListener((group, checkedId) -> mKeepAlive = (checkedId == R.id.rb_keep_alive_open));
        RadioGroup rgHistoricalRecords = findViewById(R.id.rg_historical_records);
        rgHistoricalRecords.setOnCheckedChangeListener((group, checkedId) -> mKeepHistoryRecord = (checkedId == R.id.rb_keep_open));
    }

    private void verifyInput() {
        String avatarInitConfigJson = etRtcInitConfig.getText().toString().trim();
        if (avatarInitConfigJson.isEmpty()) {
            Toast.makeText(NativeChatConfigActivity.this, "请输入RTC入会信息", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            tyAvatarInitData = new Gson().fromJson(avatarInitConfigJson, TYAvatarInitData.class);
            if (null == tyAvatarInitData.getRtcParams()) {
                throw new RuntimeException("rtc params is empty");
            }
            tyDialogConfig = new TYDialogConfig();
            tyDialogConfig.mode = mMode;
            tyDialogConfig.renderType = Constant.TYAvatarRenderType.REMOTE_RENDER_AVATAR;
            tyDialogConfig.setKeepAlive(mKeepAlive);
        } catch (Exception ex) {
            Log.e(TAG, "verifyInput failed:" + ex.getLocalizedMessage());
            Toast.makeText(this, "VerifyInputFailed:" + ex.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            tyAvatarInitData = null;
            tyDialogConfig = null;
        }

        startRTC();
    }

    public void startRTC() {
        if (NativeChatConfigActivity.this.checkPermission()) {
            launchVideoChat();
        }
    }

    /**
     * 拉起VideoChat页
     *
     * @return true or false
     */
    private boolean launchVideoChat() {
        if (null == tyAvatarInitData || null == tyDialogConfig) {
            Log.e(TAG, "launch failed without rtcConfig or dialogConfig");
            return false;
        }
        boolean startRe = VideoChatActivity.launchVideoChat(NativeChatConfigActivity.this, tyAvatarInitData, tyDialogConfig);
        Log.d(TAG, "startRTC called payload:" + tyAvatarInitData + ";dialogConfig:" + tyDialogConfig
                + ";startResult:" + startRe);
        return startRe;
    }

    private boolean checkPermission() {
        if (ContextCompat.checkSelfPermission(this, permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{permission.RECORD_AUDIO}, PERMISSION_REQUEST_CODE);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            launchVideoChat();
        }
    }
}
