import 'package:anchor_collect_flutter/controllers/ble_service.dart';
import 'package:anchor_collect_flutter/routes/routes.dart';
import 'package:anchor_collect_flutter/utils/dialog_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import 'setting_state.dart';

class SettingLogic extends GetxController {
  final SettingState state = SettingState();

  @override
  void onInit() {
    // 一开始就检查权限
    requestBlePermissions();
  }

  refreshBle() {
    if (BleService.to.isScanning.value) {
      DialogUtils.showToast('停止扫描');
    } else {
      BleService.to.scanResults.clear();
      DialogUtils.showToast('开始扫描');
    }
    BleService.to.toggleScan();
  }

  connectBle(BuildContext context, int index) {
    if (BleService.to.isConnect) {
      BleService.to.stopScan();
    }
    BleService.to.connectToDevice(index, (args) {
      BleService.to.isConnect = true;
      DialogUtils.showToast('蓝牙设备连接成功');
      // DialogUtils.dismissDialog();
      Get.back();
    });
  }

  // 检查权限
  Future<bool> requestBlePermissions() async {
    var isLocationGranted = await Permission.locationWhenInUse.request();
    print('checkBlePermissions, isLocationGranted=$isLocationGranted');

    var isBleScanGranted = await Permission.bluetoothScan.request();
    print('checkBlePermissions, isBleScanGranted=$isBleScanGranted');
    //
    var isBleConnectGranted = await Permission.bluetoothConnect.request();
    print('checkBlePermissions, isBleConnectGranted=$isBleConnectGranted');
    //
    var isBleAdvertiseGranted = await Permission.bluetoothAdvertise.request();
    print('checkBlePermissions, isBleAdvertiseGranted=$isBleAdvertiseGranted');

    return isLocationGranted == PermissionStatus.granted &&
        isBleScanGranted == PermissionStatus.granted &&
        isBleConnectGranted == PermissionStatus.granted &&
        isBleAdvertiseGranted == PermissionStatus.granted;
  }
}
