import 'package:get/get.dart';
import 'package:vitalapp/managers/interfaces/permission.dart';
import 'package:vitalapp/pages/controllers/blue_location_mixin.dart';
import 'package:vnote_device_plugin/consts/types.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 'package:fis_common/logger/logger.dart';

import 'state.dart';

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

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

  @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("正在绑定设备...");

    logger.i("正在绑定设备 ${deviceInfo.type}");
    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("正在解除绑定...");
    logger.i("正在绑定设备 $type");
    await _deviceManager.removeDeviceByType(type);
    await _loadDeviceList();

    cancelBusy();
  }

  ///验证是否有权限搜索设备
  Future<bool> initPermission() async {
    var result = await _permissionManager.requestPermissions([
      'Location',
      'BluetoothConnect',
      'BluetoothScan',
      'BluetoothAdvertise',
    ]);
    return result;
  }

  Future<bool> openAppSettingsAsync() async {
    return await _permissionManager.openAppSettingsAsync();
  }

  void _loadData() async {
    final types = await _deviceManager.getAccessTypes();
    types.remove(DeviceTypes.WAIST); // TODO: 腰围尺尚未支持
    state.accessTypes = types;
    await _loadDeviceList();
  }

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