package xn.xxp.home.setting;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ResourceUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hikvision.dmb.EthernetConfig;
import com.hikvision.dmb.display.InfoDisplayApi;
import com.hikvision.dmb.network.InfoNetworkApi;
import com.hikvision.dmb.system.InfoSystemApi;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.njlz.card.DeviceUtils;

import xn.xxp.R;
import xn.xxp.databinding.ActivitySettingBinding;
import xn.xxp.room.RoomTool;
import xn.xxp.room.bean.DeviceConfig;
import xn.xxp.room.dao.DeviceConfigDao;
import xn.xxp.utils.Tool;

@SuppressLint("SetTextI18n")
public class SettingActivity extends AppCompatActivity {
    private ActivitySettingBinding binding;

    private DeviceConfig deviceConfig;
    private DeviceConfigDao deviceConfigDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySettingBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        try {
            deviceConfigDao = RoomTool.getInstance().deviceConfigDao();
            deviceConfig = deviceConfigDao.getDeviceConfig();
            if (null == deviceConfig) {
                deviceConfig = new DeviceConfig();
            }
            // 状态栏
            binding.statusSwitch.setChecked(InfoDisplayApi.getStatusBarEnable());
            binding.statusSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> InfoDisplayApi.setStatusBarEnable(isChecked));
            // 导航栏
            binding.navSwitch.setChecked(InfoDisplayApi.getNavigationBarEnable());
            binding.navSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> InfoDisplayApi.setNavigationBarEnable(isChecked));
            // app版本
            binding.varBT.setText("版本:" + AppUtils.getAppVersionName());
            String sn = InfoSystemApi.getSerialNumber();
            // 设备sn
            binding.snBT.setText("SN:" + (TextUtils.isEmpty(sn) ? "NULL" : sn));
            // 网络ip
            EthernetConfig ethernetConfig = InfoNetworkApi.getEthernetConfig();
            String ip = ethernetConfig.getIpAddress();
            binding.ipBT.setText("Ip:" + (TextUtils.isEmpty(ip) ? "NULL" : ip));
            // 启动文件管理
            binding.fileBrowserBT.setOnClickListener(v -> Tool.INSTANCE.openFileBrowser());
            // 重启设备
            binding.rebootBT.setOnClickListener(v ->
                    MessageDialog.show("Tips",
                                    "确认要重启该设备么?",
                                    "确认",
                                    "取消")
                            .setOkButtonClickListener((dialog, v1) -> {
                                InfoSystemApi.reboot();
                                return false;
                            }));
            // 退出应用
            binding.exitBT.setOnClickListener(v ->
                    MessageDialog.show("Tips",
                                    "确认要退出该应用么?",
                                    "确认",
                                    "取消")
                            .setOkButtonClickListener((dialog, v1) -> {
                                Tool.INSTANCE.exitApp();
                                return false;
                            }));
            // 系统设置
            binding.settingBT.setOnClickListener(v -> {
                Tool.INSTANCE.openSetting();
                Tool.INSTANCE.exitApp();
            });
            // 超级权限
            if (SPUtils.getInstance().getBoolean("isRoot", false)) {
                binding.rootCV.setVisibility(View.VISIBLE);
            }
            // Http服务器
            binding.httpUriET.setText(deviceConfig.getBaseUrl());
            // mqtt服务器
            binding.mqttUserNameET.setText(deviceConfig.getMqttName());
            binding.mqttPassWordET.setText(deviceConfig.getMqttPas());
            binding.mqttUriET.setText(deviceConfig.getMqttAddress());
            // 密码
            binding.oldPasswordET.setText(deviceConfig.getAdminPas());
            // 保存
            binding.save.setOnClickListener(v -> saveAndReStart());
            // 人脸
            binding.faceBT.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityUtils.startActivity(FaceListActivity.class);
                }
            });
            // 锁
            binding.lock.setOnCheckedChangeListener((buttonView, isChecked) -> {
                DeviceUtils.setElectricLock(1, isChecked);
                if (isChecked) {
                    ToastUtils.showLong("开锁后需要手动关锁");
                }
            });

            binding.testBaseUrlBT.setOnClickListener(v -> binding.httpUriET.setText("http://192.168.1.8/api/"));
            binding.xnBaseUrlBT.setOnClickListener(v -> binding.httpUriET.setText("http://10.148.100.82/api/"));
            binding.testMqttBT.setOnClickListener(v -> binding.mqttUriET.setText("tcp://192.168.1.8:1883"));
            binding.xnMqttBT.setOnClickListener(v -> binding.mqttUriET.setText("tcp://10.148.100.82:31072"));
        } catch (Exception e) {
            LogUtils.e(Log.getStackTraceString(e));
        }
    }


    /**
     * 保存并重启应用
     */
    private void saveAndReStart() {
        // http服务
        Editable httpUriETText = binding.httpUriET.getText();
        if (null == httpUriETText || TextUtils.isEmpty(httpUriETText) || !RegexUtils.isURL(httpUriETText.toString())) {
            binding.httpUriET.setError("请正确输入Http服务地址!", ResourceUtils.getDrawable(R.drawable.ic_et_err));
            return;
        }
        deviceConfig.setBaseUrl(httpUriETText.toString());
        // mqtt账号
        Editable mqttUserNameETText = binding.mqttUserNameET.getText();
        if (null == mqttUserNameETText || TextUtils.isEmpty(mqttUserNameETText)) {
            binding.mqttUserNameET.setError("请正确输入Mqtt账号!", ResourceUtils.getDrawable(R.drawable.ic_et_err));
            return;
        }
        deviceConfig.setMqttName(mqttUserNameETText.toString());
        // mqtt密码
        Editable mqttPassWordETText = binding.mqttPassWordET.getText();
        if (null == mqttPassWordETText || TextUtils.isEmpty(mqttPassWordETText)) {
            binding.mqttPassWordET.setError("请正确输入Mqtt密码!", ResourceUtils.getDrawable(R.drawable.ic_et_err));
            return;
        }
        deviceConfig.setMqttPas(mqttPassWordETText.toString());
        // mqtt服务
        Editable mqttUriETText = binding.mqttUriET.getText();
        if (null == mqttUriETText || TextUtils.isEmpty(mqttUriETText) || !RegexUtils.isURL(mqttUriETText.toString())) {
            binding.mqttUriET.setError("请正确输入Mqtt服务地址!", ResourceUtils.getDrawable(R.drawable.ic_et_err));
            return;
        }
        deviceConfig.setMqttAddress(mqttUriETText.toString());
        // 旧密码
        Editable oldPasswordETText = binding.oldPasswordET.getText();
        if (null == oldPasswordETText || TextUtils.isEmpty(oldPasswordETText)) {
            binding.oldPasswordET.setError("请正确输入密码!", ResourceUtils.getDrawable(R.drawable.ic_et_err));
            return;
        }
        deviceConfig.setAdminPas(oldPasswordETText.toString());
        deviceConfigDao.insert(deviceConfig);
        ToastUtils.showShort("即将重启App");
        ThreadUtils.runOnUiThreadDelayed(() -> Tool.INSTANCE.reStartApp("主动重启"), 1500);
    }

    @Override
    public void onBackPressed() {
    }
}