package com.videogo.ui.others;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.videogo.exception.BaseException;
import com.videogo.global.ValueKeys;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.openapi.bean.EZStorageStatus;
import com.videogo.openapi.bean.EZUserInfo;
import com.videogo.ui.login.SdkInitParams;
import com.videogo.util.SpTool;
import com.videogo.widget.TitleBar;
import com.videogo.widget.testlist.TestItem;
import com.videogo.widget.testlist.TestItemAdapter;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

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

import static com.videogo.EzvizApplication.getOpenSDK;

public class EZInterfaceTestActivity extends RootActivity {

    private String mSingleDeviceSerial = "";
    private ListView listView;
    private TitleBar titleBar;
    private List<TestItem> testItems;
    private TestItemAdapter adapter;

    /***************** 生命周期|life cycle *******************/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ezinterface_test);
        
        initViews();
        setupDataArray();
        setupListView();
    }

    /**
     * 初始化视图
     */
    private void initViews() {
        titleBar = findViewById(R.id.title_bar);
        titleBar.setTitle("接口测试");
        titleBar.addBackButton(view -> finish());
        
        listView = findViewById(R.id.list_view);
    }

    /**
     * 配置功能数组
     */
    private void setupDataArray() {
        testItems = new ArrayList<>();
        
        // 格式: [标题, 方法名]
        testItems.add(new TestItem("获取设备列表（支持网关子设备）", "onClickGetDeviceListEx"));
        testItems.add(new TestItem("获取设备信息（支持网关子设备）", "onClickGetDeviceInfoEx"));
        testItems.add(new TestItem("抓图", "onClickCaptureCamera"));
        testItems.add(new TestItem("获取用户信息", "onClickGetUserInfo"));
        testItems.add(new TestItem("SD卡格式化", "onClickFormatStorage"));
        testItems.add(new TestItem("云台结束转动Mix", "onClickPtzStopMix"));
        testItems.add(new TestItem("刷新设备详情数据", "onClickRefreshDeviceInfo"));
        testItems.add(new TestItem("绑定在NVR下的IPC设备录像直查", "onClickIPCRecordDirectQuery"));
    }

    /**
     * 设置ListView
     */
    private void setupListView() {
        adapter = new TestItemAdapter(this, testItems);
        listView.setAdapter(adapter);
        
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                handleItemClick(position);
            }
        });
    }

    /**
     * 处理列表项点击事件 - 使用反射调用对应方法
     */
    private void handleItemClick(int position) {
        TestItem item = testItems.get(position);
        String methodName = item.getClassName();
        
        try {
            Method method = this.getClass().getDeclaredMethod(methodName);
            method.setAccessible(true);
            method.invoke(this);
        } catch (Exception e) {
            e.printStackTrace();
            showToast("方法调用失败: " + e.getMessage());
        }
    }

    /***************** 接口方法 *******************/

    /**
     * 获取设备列表（支持网关子设备）
     */
    private void onClickGetDeviceListEx() {
        new Thread(() -> {
            try {
                List<EZDeviceInfo> list = getOpenSDK().getDeviceListEx(0, 10);
            } catch (BaseException e) {
                e.printStackTrace();
            }
            requestSuccess();
        }).start();
    }

    /**
     * 获取设备信息（支持网关子设备）
     */
    private void onClickGetDeviceInfoEx() {
        if (!isExistDeviceSerial()) return;
        new Thread(() -> {
            try {
                EZDeviceInfo deviceInfo = getOpenSDK().getDeviceInfoEx(mSingleDeviceSerial);
            } catch (BaseException e) {
                e.printStackTrace();
            }
            requestSuccess();
        }).start();
    }

    /**
     * 抓图
     */
    private void onClickCaptureCamera() {
        if (!isExistDeviceSerial()) return;
        new Thread(() -> {
            try {
                String string = getOpenSDK().captureCamera(mSingleDeviceSerial, 1);
            } catch (BaseException e) {
                e.printStackTrace();
            }
            requestSuccess();
        }).start();

    }

    /**
     * 获取用户信息
     */
    private void onClickGetUserInfo() {
        new Thread(() -> {
            try {
                EZUserInfo userInfo = getOpenSDK().getUserInfo();
            } catch (BaseException e) {
                e.printStackTrace();
            }
            requestSuccess();
        }).start();
    }

    /**
     * SD卡格式化
     */
    private void onClickFormatStorage() {
        if (!isExistDeviceSerial()) return;
        new Thread(() -> {
            try {
                List<EZStorageStatus> storageStatusList = getOpenSDK().getStorageStatus(mSingleDeviceSerial);
                if (storageStatusList != null && storageStatusList.size() > 0) {
                    EZStorageStatus info = storageStatusList.get(0);
                    getOpenSDK().formatStorage(mSingleDeviceSerial, info.getIndex());
                    requestSuccess();
                }
            } catch (BaseException e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 云台结束转动Mix
     */
    private void onClickPtzStopMix() {
        if (!isExistDeviceSerial()) return;
        new Thread(() -> {
            try {
                boolean result = getOpenSDK().controlPTZMix(mSingleDeviceSerial, 1,
                        EZConstants.EZPTZCommand.EZPTZCommandUp, EZConstants.EZPTZAction.EZPTZActionSTOP, 2);
                requestSuccess();
            } catch (BaseException e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 刷新设备详情数据
     */
    private void onClickRefreshDeviceInfo() {
        if (!isExistDeviceSerial()) return;
        new Thread(() -> {
            try {
                getOpenSDK().refreshDeviceDetailInfo(mSingleDeviceSerial, 1);
                requestSuccess();
            } catch (BaseException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void onClickIPCRecordDirectQuery() {
        if (!isExistDeviceSerial()) return;
        EZDeviceRecordDirectQueryActivity.launch(this, mSingleDeviceSerial);
    }

    /***************** 其他自定义方法 *******************/

    private boolean isExistDeviceSerial() {
        // 只展示单个设备
        String sdkInitParamStr = SpTool.obtainValue(ValueKeys.SDK_INIT_PARAMS);
        if (sdkInitParamStr != null) {
            SdkInitParams mInitParams = new Gson().fromJson(sdkInitParamStr, SdkInitParams.class);
            mSingleDeviceSerial = mInitParams.specifiedDevice;
        }
        if (TextUtils.isEmpty(mSingleDeviceSerial)) {
            showToast(R.string.test_specify_device_tip);
            return false;
        }
        return true;
    }

    private void requestSuccess() {
        runOnUiThread(() -> showToast(R.string.test_request_success_tip));
    }

}