package com.phlx.anchorcollect_p.ui.setting;

import android.app.ActivityManager;
import android.app.Application;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.phlx.anchorcollect_p.App;
import com.phlx.anchorcollect_p.BR;
import com.phlx.anchorcollect_p.R;
import com.phlx.anchorcollect_p.ble.BluetoothEntity;
import com.phlx.anchorcollect_p.bt.BtService;
import com.phlx.anchorcollect_p.data.Repository;
import com.phlx.anchorcollect_p.event.EventMsg;
import com.phlx.anchorcollect_p.event.EventTag;
import com.phlx.anchorcollect_p.rfid.ModuleManager;
import com.phlx.anchorcollect_p.util.TextUtil;
import com.uhf.structures.Rfid_Value;

import java.util.ArrayList;
import java.util.List;

import cn.wandersnail.ble.Device;
import cn.wandersnail.bluetooth.BTManager;
import cn.wandersnail.bluetooth.DiscoveryListener;
import cn.wandersnail.commons.util.ToastUtils;
import io.reactivex.disposables.Disposable;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class SettingVM extends BaseViewModel<Repository> implements DiscoveryListener {


    //给RecyclerView添加ObservableList
    public ObservableList<BLEItem> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<BLEItem> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_ble);

    private Device curDevice;


    //选中的蓝牙设备信息
    public static BluetoothEntity bluetoothEntity;

    //当前蓝牙搜索集合
    private List<BluetoothEntity> bluetoothList;

    public SingleLiveEvent<Integer> btRequestEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> btParamEvent = new SingleLiveEvent<>();

    //错误提示
    public SingleLiveEvent<String> errorEvent = new SingleLiveEvent<>();
    //关闭页面
    public SingleLiveEvent<String> closeEvent = new SingleLiveEvent<>();

    //功率
    public ObservableField<String> power = new ObservableField<>("");


    private Disposable weightBus;

    public SettingVM(@NonNull Application application, Repository model) {
        super(application, model);

        initData();

    }


    private void initData() {

    }

    //获取功率
    public BindingCommand getPowerOnClick = new BindingCommand(this::getAntennaPower);
    //设置功率
    public BindingCommand setPowerOnClick = new BindingCommand(this::setAntennaPower);


    /**
     * 获取天线功率
     */
    private void getAntennaPower() {
        if (ModuleManager.powerOn() != 0) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("模块连接失败");
            ModuleManager.powerOff();
            return;
        }
        Rfid_Value power_value = new Rfid_Value();
        int powerStatue =
                App.getInstance().getLinkage().Radio_GetAntennaPower(power_value);
        if (powerStatue == 0) {
            String value = String.valueOf((power_value.value) / 10);
            power.set(value);
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("获取天线功率成功");
        } else {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("获取天线功率失败");
        }

    }

    /**
     * 设置天线功率
     */
    private void setAntennaPower() {
        if (ModuleManager.powerOn() != 0) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("模块连接失败");
            ModuleManager.powerOff();
            return;
        }
        if (TextUtil.isSpace(power.get())) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("功率不能为空");
            return;
        }
        int status_power;
        int iu32 = (int) (Double.parseDouble(power.get()) * 10);
        if (iu32 < 0) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("参数不可用");
            return;
        }
        status_power = App.getInstance().getLinkage().Radio_SetAntennaPower(iu32);

        if (status_power == 0) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("功率修改成功");

        } else if (status_power == -1000) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("正在盘点");
        } else {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("设置功率失败");
        }
    }

    public void initBt(Context context) {

        bluetoothList = new ArrayList<>();
        BTManager.isDebugMode = true;
        BTManager.getInstance().addDiscoveryListener(this);
        btParamEvent.call();
    }

    public BindingCommand OnRefreshClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
//            BTManager.getInstance().stopDiscovery();
//            doStartDiscovery();
        }
    });

    private void doStartDiscovery() {
//        observableList.clear();
//        bluetoothList.clear();
//        BTManager.getInstance().startDiscovery();
    }

    public BindingCommand OnStopClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
//            BTManager.getInstance().stopDiscovery();
        }
    });

    public BindingCommand OnConnectionClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

        }
    });

    public BindingCommand OnDisconnectionClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            //断开指定连接
            stopBtService();
            if (bluetoothEntity != null)
                BTManager.getInstance().disconnectConnection(bluetoothEntity.getBluetoothDevice());
        }
    });


    public void itemOnClick(BluetoothEntity btEntity) {
        BTManager.getInstance().stopDiscovery();
        stopBtService();
        bluetoothEntity = btEntity;

//        showDialog("正在链接蓝牙...");

        Intent intent = new Intent(getApplication(), BtService.class);
        intent.putExtra("device", bluetoothEntity.getBluetoothDevice());
        if (!isServiceRunning(getApplication()))
            getApplication().startService(intent);
    }


    @Override
    public void onDiscoveryStart() {

    }

    @Override
    public void onDiscoveryStop() {

    }

    @Override
    public void onDeviceFound(@NonNull BluetoothDevice device, int rssi) {
        if (!TextUtils.isEmpty(device.getName())) {
            BluetoothEntity entity = new BluetoothEntity();
            entity.setName(device.getName());
            entity.setAddress(device.getAddress());
            entity.setRssi(rssi);
            entity.setBluetoothDevice(device);
            if (!bluetoothList.contains(entity)) {
                bluetoothList.add(entity);
                BLEItem bleItem = new BLEItem(this, entity);
                observableList.add(bleItem);
            }
        }
    }

    @Override
    public void onDiscoveryError(int errorCode, @NonNull String errorMsg) {
        switch (errorCode) {
            case DiscoveryListener.ERROR_LACK_LOCATION_PERMISSION://缺少定位权限
                ToastUtils.showShort("搜索出错：缺少定位权限" + errorCode);
                break;
            case DiscoveryListener.ERROR_LOCATION_SERVICE_CLOSED://位置服务未开启
                ToastUtils.showShort("搜索出错：位置服务未开启" + errorCode);
                break;
            case DiscoveryListener.ERROR_LACK_SCAN_PERMISSION://缺少搜索权限
                ToastUtils.showShort("搜索出错：缺少搜索权限" + errorCode);
                break;
            case DiscoveryListener.ERROR_SCAN_FAILED://搜索失败
                ToastUtils.showShort("搜索出错：" + errorCode);
                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (BTManager.getInstance().isInitialized()) {
            BTManager.getInstance().stopDiscovery();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("Main", "onResume");
        if (BTManager.getInstance().isInitialized()) {
            if (BTManager.getInstance().isBluetoothOn()) {
//                doStartDiscovery();
            } else {
                //未开启蓝牙
                btRequestEvent.call();
            }
        }
    }

    /**
     * 判断服务是否在运行中
     *
     * @param context 即为Context对象
     * @return 是否在运行中
     */
    private boolean isServiceRunning(Context context) {
        if (context != null) {
            ActivityManager activityManager
                    = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            ArrayList<ActivityManager.RunningServiceInfo> runningServiceInfoList
                    =
                    (ArrayList<ActivityManager.RunningServiceInfo>) activityManager.getRunningServices(100);
            for (ActivityManager.RunningServiceInfo runningServiceInfo : runningServiceInfoList) {
                if ("BtService".equals(runningServiceInfo.service.getClassName())) {
                    return true;
                }
            }
        } else {
            return false;
        }
        return false;
    }


    public void stopBtService() {
        if (isServiceRunning(getApplication())) {
            Intent intent = new Intent(getApplication(), BtService.class);
            getApplication().stopService(intent);
        }
    }


    @Override
    public void registerRxBus() {
        super.registerRxBus();
        weightBus =
                RxBus.getDefault().toObservable(EventMsg.class).subscribe(eventType -> {
                    if (eventType.getAction().equals(EventTag.EVENT_BT_SUCC)) {
                        ToastUtils.showShort("蓝牙链接成功");
//                        closeEvent.call();
                    }else if(eventType.getAction().equals(EventTag.EVENT_BT_FAIL)){
                        ToastUtils.showShort("蓝牙链接失败");
                    }
                });
        RxSubscriptions.add(weightBus);
    }

    @Override
    public void removeRxBus() {
        super.removeRxBus();
        RxSubscriptions.remove(weightBus);
    }



}
