package com.videogo.ui.login.helper;

import android.app.Activity;
import android.app.Dialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.videogo.global.GlobalKit;
import com.videogo.util.Utils;

import org.json.JSONObject;

import ezviz.ezopensdk.R;

import static com.videogo.EzvizApplication.getOpenSDK;

/**
 * 测试专用 - 小权限 TKToken 批量设置工具类
 * 包含弹框输入、解析 JSON、设置设备级 token 等测试辅助方法
 */
public class TKTokenTestHelper {

    // JSON 字段名常量
    private static final String KEY_APP_KEY = "appKey";
    private static final String KEY_HTTP_TOKEN = "httpToken";
    private static final String KEY_DEVICE_SERIAL = "deviceSerial";
    private static final String KEY_DEVICE_TOKEN = "deviceToken";
    private static final String KEY_DEVICE_GLOBAL_TOKEN = "deviceGlobalToken";
    private static final String KEY_DEVICE_VIDEO_TOKEN = "deviceVideoToken";
    private static final String KEY_CHANNEL_NO = "channelNo";
    private static final String KEY_PREVIEW_STREAM_TOKEN = "previewStreamToken";
    private static final String KEY_TALK_STREAM_TOKEN = "talkStreamToken";
    private static final String KEY_PLAYBACK_STREAM_TOKEN = "playbackStreamToken";

    private final Activity mActivity;
    // 缓存弹框输入的token JSON，SDK初始化后再设置设备级token
    private JSONObject mPendingTokenDict;

    public TKTokenTestHelper(Activity activity) {
        mActivity = activity;
    }

    /**
     * 测试专用-小权限token批量设置弹框
     *
     * @param appKeyET       AppKey 输入框
     * @param tokenET        AccessToken 输入框
     * @param deviceET       指定设备序列号输入框
     */
    public void showTKTokenBatchSetupDialog(EditText appKeyET, EditText tokenET, EditText deviceET) {
        final Dialog dialog = new Dialog(mActivity, R.style.IOSAlertDialogStyle);
        dialog.setContentView(R.layout.dialog_ios_multi_input);
        dialog.setCanceledOnTouchOutside(true);

        android.view.Window window = dialog.getWindow();
        if (window != null) {
            window.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(lp);
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                    | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        }

        TextView titleTv = dialog.findViewById(R.id.tv_ios_dialog_title);
        LinearLayout inputContainer = dialog.findViewById(R.id.ll_ios_dialog_input_container);
        TextView negativeBtn = dialog.findViewById(R.id.btn_ios_dialog_negative);
        TextView positiveBtn = dialog.findViewById(R.id.btn_ios_dialog_positive);

        titleTv.setText("测试专用-小权限token批量设置");

        final EditText inputET = new EditText(mActivity);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                Utils.dip2px(mActivity, 36));
        inputET.setLayoutParams(lp);
        inputET.setTextSize(14);
        inputET.setTextColor(0xFF000000);
        inputET.setHintTextColor(0xFF999999);
        inputET.setSingleLine(true);
        inputET.setHint("请输入js脚本生成的小权限token json字符串");
        inputET.setPadding(Utils.dip2px(mActivity, 12), 0,
                Utils.dip2px(mActivity, 12), 0);
        inputET.setBackgroundResource(R.drawable.bg_ios_dialog_input);
        inputContainer.addView(inputET);

        negativeBtn.setOnClickListener(v -> dialog.dismiss());
        positiveBtn.setOnClickListener(v -> {
            String jsonStr = inputET.getText().toString().trim();
            if (TextUtils.isEmpty(jsonStr)) {
                showToast("输入内容不能为空");
                return;
            }
            try {
                JSONObject dict = new JSONObject(jsonStr);
                // 设置appKey和accessToken到输入框
                if (dict.has(KEY_APP_KEY)) {
                    appKeyET.setText(dict.getString(KEY_APP_KEY));
                }
                if (dict.has(KEY_HTTP_TOKEN)) {
                    tokenET.setText(dict.getString(KEY_HTTP_TOKEN));
                }
                // 设置指定设备序列号
                if (dict.has(KEY_DEVICE_SERIAL)) {
                    deviceET.setText(dict.getString(KEY_DEVICE_SERIAL));
                }
                // 设置设备级tkToken（缓存dict，等SDK初始化后设置）
                mPendingTokenDict = dict;
                // 设置预览/对讲/回放取流token
                if (dict.has(KEY_PREVIEW_STREAM_TOKEN)) {
                    GlobalKit.getInstance().previewStreamToken = dict.getString(KEY_PREVIEW_STREAM_TOKEN);
                }
                if (dict.has(KEY_TALK_STREAM_TOKEN)) {
                    GlobalKit.getInstance().talkStreamToken = dict.getString(KEY_TALK_STREAM_TOKEN);
                }
                if (dict.has(KEY_PLAYBACK_STREAM_TOKEN)) {
                    GlobalKit.getInstance().playbackStreamToken = dict.getString(KEY_PLAYBACK_STREAM_TOKEN);
                }
                dialog.dismiss();
                showToast("小权限token批量设置成功");
            } catch (Exception e) {
                e.printStackTrace();
                showToast("JSON解析失败，请检查格式");
            }
        });

        dialog.show();
    }

    /**
     * SDK初始化后，设置缓存的设备级token
     */
    public void applyPendingDeviceTokens() {
        if (mPendingTokenDict == null) {
            return;
        }
        try {
            String deviceSerial = mPendingTokenDict.optString(KEY_DEVICE_SERIAL, null);
            // 设备级token
            if (deviceSerial != null && mPendingTokenDict.has(KEY_DEVICE_TOKEN)) {
                getOpenSDK().setDeviceToken(deviceSerial, mPendingTokenDict.getString(KEY_DEVICE_TOKEN));
            }
            // 设备通道级token
            if (deviceSerial != null && mPendingTokenDict.has(KEY_DEVICE_GLOBAL_TOKEN) && mPendingTokenDict.has(KEY_DEVICE_VIDEO_TOKEN)) {
                int channelNo = mPendingTokenDict.optInt(KEY_CHANNEL_NO, 1);
                getOpenSDK().setDeviceToken(deviceSerial, channelNo,
                        mPendingTokenDict.getString(KEY_DEVICE_GLOBAL_TOKEN), mPendingTokenDict.getString(KEY_DEVICE_VIDEO_TOKEN));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mPendingTokenDict = null;
    }

    private void showToast(String msg) {
        Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
    }
}
