package com.tongyi.videochatdemo;

import android.Manifest.permission;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
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.TYAvatarRenderType;
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.common.util.DeviceUtil;
import com.tongyi.videochatdemo.databinding.ActivityNativeChatConfigBinding;

/**
 * @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 TYAvatarInitData tyAvatarInitData;
    private TYDialogConfig tyDialogConfig;
    private String mChatMode = TYVoiceChatMode.TAP2TALK;
    private String mRenderType = TYAvatarRenderType.REMOTE_RENDER_AVATAR;// 默认云渲染
    /**
     * 数字人说话的音频采样率
     * 云渲染和端渲染，采样率是固定的48K
     * 单独数字人模式，采样率可由用户自定义，Demo里测试音频的采样率是16K
     */
    private int mSampleRate = 48000;
    private boolean mKeepAlive = true;
    private ActivityNativeChatConfigBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DeviceUtil.setStatusBarColor(this);
        binding = ActivityNativeChatConfigBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initView();
        checkPermission();

        // 输出App的包名/签名/设备ID
        String packageName = DeviceUtil.getPackageName(this);
        String deviceId = DeviceUtil.getDeviceId(this);
        String signature = DeviceUtil.getSignatureSha256(this);
        Log.d(TAG, "packageName: " + packageName + ", deviceId: " + deviceId + ", signature: " + signature);
    }

    private void initView() {

        // RTC入会信息示例, avatarAssets端侧渲染数字人必填，云端渲染数字人可不填
        String initData = "{\n" +
                "    \"avatarAssets\": {\n" +
                "        \"md5\": \"ACAABCXXXXXXXXCEDCA96A1CC2169848\",\n" +
                "        \"minRequiredVersion\": \"0.0.2\",\n" +
                "        \"secret\": \"XXXXXXX+t7ShPeKPlDUHG6FcGKwpT9LEcovF3oRWEIjWEbL6Dltf20HI/XXXXXXXXX/JAXtZ6ZCOYeHXG1wu6mJ186X2fy7kEz0uXLLCuHrKMBgVprONLTzUaUzasQhaJyZibIrSwP/WVqDq4x5QLmxWpSIf3di+Dc7xo463Ysd2ppazZnMQTgcGRrfgQ1n6YXynzuhMkNF0TR4KP3uQdZRi1oVeXt+R/r3PAw2oHQN6oFZwhOx5KOUCg7a9Wt60mrAQ/Ub9kqlVTmm2wNEM23LTVRIIQ==\",\n" +
                "        \"type\": \"AVATAR_2D_MOBILE\",\n" +
                "        \"url\": \"https://daily-avatar-property.oss-cn-beijing.aliyuncs.com/avatar-share-property/AVATAR_2D_MOBILE/Mt.CQKY55EXBBYU2/secret_assets_android.zip?Expires=1765976701\"\n" +
                "    },\n" +
                "    \"rtcParams\": {\n" +
                "        \"appId\": \"470552b0-9401-4b2c-8456-df39f2e5a986\",\n" +
                "        \"avatarUserId\": \"avatar-8504256390345063\",\n" +
                "        \"channel\": \"8474076537974584\",\n" +
                "        \"clientUserId\": \"client-8677138898148002\",\n" +
                "        \"gslb\": \"https://gw.rtn.aliyuncs.com\",\n" +
                "        \"nonce\": \"\",\n" +
                "        \"serverUserId\": \"system-6956483516401508\",\n" +
                "        \"timestamp\": 1766059500,\n" +
                "        \"token\": \"4857c6f7b127a11dbf122a68ac48a1637f9693c3d0d5fd4bf91c39a2c73ed882\"\n" +
                "    },\n" +
                "    \"sessionId\": \"E89428D7-FD74-487A-A7B3-0EFF3A0AA43C\"\n" +
                "}";
//        binding.etRtcInitConfig.setText(initData);

        // License示例
        String license = "941ea11378a5cc9b94abfeb06f255ab8adedbcxxxxxxxxxxxxxxxx";
//        binding.etLicense.setText(license);

        binding.btStartChat.setOnClickListener(view -> verifyInput());

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

        final RadioButton[] rbViews = {binding.rbRenderRemote, binding.rbRenderLocal, binding.rbRenderRemoteAvatarOnly, binding.rbRenderLocalAvatarOnly};
        final View.OnClickListener rbOnClickListener = v -> {
            if (!(v instanceof CompoundButton)) {
                return;
            }
            ((CompoundButton) v).setChecked(true);
            for (RadioButton rbView : rbViews) {
                if (rbView == v) {
                    continue;
                }
                rbView.setChecked(false);
            }
        };
        final CompoundButton.OnCheckedChangeListener rbOnCheckedChangeListener = (buttonView, isChecked) -> {
            if (!isChecked) {
                return;
            }
            int checkedId = buttonView.getId();
            if (checkedId == R.id.rb_render_remote) {
                mRenderType = TYAvatarRenderType.REMOTE_RENDER_AVATAR;
                mSampleRate = 48000;
            } else if (checkedId == R.id.rb_render_remote_avatar_only) {
                mRenderType = TYAvatarRenderType.REMOTE_RENDER_AVATAR_ONLY;
                mSampleRate = 16000;
            } else if (checkedId == R.id.rb_render_local) {
                mRenderType = TYAvatarRenderType.LOCAL_RENDER_AVATAR;
                mSampleRate = 48000;
            } else {
                mRenderType = TYAvatarRenderType.LOCAL_RENDER_AVATAR_ONLY;
                mSampleRate = 16000;
            }
            Log.d(TAG, "select renderType:" + mRenderType + ";sampleRate:" + mSampleRate);
        };
        binding.rbRenderRemote.setOnClickListener(rbOnClickListener);
        binding.rbRenderRemoteAvatarOnly.setOnClickListener(rbOnClickListener);
        binding.rbRenderLocal.setOnClickListener(rbOnClickListener);
        binding.rbRenderLocalAvatarOnly.setOnClickListener(rbOnClickListener);
        binding.rbRenderRemote.setOnCheckedChangeListener(rbOnCheckedChangeListener);
        binding.rbRenderRemoteAvatarOnly.setOnCheckedChangeListener(rbOnCheckedChangeListener);
        binding.rbRenderLocal.setOnCheckedChangeListener(rbOnCheckedChangeListener);
        binding.rbRenderLocalAvatarOnly.setOnCheckedChangeListener(rbOnCheckedChangeListener);

        binding.rgKeepAlive.setOnCheckedChangeListener((group, checkedId) -> mKeepAlive = (checkedId == R.id.rb_keep_alive_open));
    }

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

        try {
            // 1、校验RTC信息，无论云端渲染还是端侧渲染，都需要通过RTC传输信令
            tyAvatarInitData = new Gson().fromJson(avatarInitConfigJson, TYAvatarInitData.class);
            if (null == tyAvatarInitData.getRtcParams()) {
                Toast.makeText(this, "rtc params is empty", Toast.LENGTH_SHORT).show();
                return;
            }

            // 2、端侧渲染，需额外校验License/资产等信息
            String license = binding.etLicense.getText().toString().trim();
            boolean renderLocal = TYAvatarRenderType.LOCAL_RENDER_AVATAR.equals(mRenderType)
                    || TYAvatarRenderType.LOCAL_RENDER_AVATAR_ONLY.equals(mRenderType);
            if (renderLocal) {
                if (TextUtils.isEmpty(license)) {
                    Toast.makeText(this, "端侧渲染请输入License", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (null == tyAvatarInitData.getAvatarAssets() || TextUtils.isEmpty(tyAvatarInitData.getAvatarAssets().getMd5())) {
                    Toast.makeText(this, "端侧渲染请输入资产信息", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            tyDialogConfig = new TYDialogConfig();
            tyDialogConfig.mode = mChatMode;
            tyDialogConfig.renderType = mRenderType;
            tyDialogConfig.setLicense(license);
            tyDialogConfig.setKeepAlive(mKeepAlive);
            tyDialogConfig.setAvatarBlendShapeScale(1.5f);// 端数字人表情缩放系数，值域[0, 3.0]
            tyDialogConfig.setOutboundSampleRate(mSampleRate);
        } catch (Exception ex) {
            Log.e(TAG, "verifyInput failed:" + ex.getLocalizedMessage());
            Toast.makeText(this, "VerifyInputFailed:" + ex.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            tyAvatarInitData = null;
            tyDialogConfig = null;
        }

        start();
    }

    public void start() {
        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, "launchVideoChat 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();
        }
    }
}
