import 'package:get/get.dart';
import 'package:vnote_device_plugin/models/device.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/managers/interfaces/device.dart';
import 'package:vitalapp/managers/interfaces/models/device.dart';

import 'state.dart';

class DevicesSettingController extends FControllerBase {
  final state = DevicesSettingState();

  final _deviceManager = Get.find<IDeviceManager>();

  @override
  void onReady() {
    super.onReady();
    _loadData();
  }

  DeviceModel? getDataByType(String type) {
    final data = state.deviceList.firstWhereOrNull((e) => e.type == type);
    return data;
  }

  /// 绑定设备
  ///
  /// [deviceInfo] 设备信息
  void bindDevice(DeviceInfo deviceInfo) async {
    setBusy("正在绑定设备...");

    final model = DeviceModel(
      bleName: deviceInfo.bleName,
      productName: deviceInfo.productName,
      mac: deviceInfo.mac,
      model: deviceInfo.model,
      type: deviceInfo.type,
    );

    await _deviceManager.addDevice(model);
    await _loadDeviceList();

    cancelBusy();
  }

  /// 解绑设备
  ///
  /// [type] 设备类型
  void unbindDevice(String type) async {
    setBusy("正在解除绑定...");

    await _deviceManager.removeDeviceByType(type);
    await _loadDeviceList();

    cancelBusy();
  }

  void _loadData() async {
    state.accessTypes = await _deviceManager.getAccessTypes();
    await _loadDeviceList();
  }

  Future<void> _loadDeviceList() async {
    state.deviceList = await _deviceManager.getDeviceList();
  }
}
