import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/devices/base.dart';
import 'package:vitalapp/managers/interfaces/permission.dart';
import 'package:vitalapp/pages/medical/models/worker.dart';

abstract class BaseDeviceController<T extends DeviceWorkerBase>
    extends GetxController {
  BaseDeviceController(this.model, this.mac) {
    worker = createWorker();
  }
  late final T worker;
  late WorkerStatus connectStatus = WorkerStatus.connecting;
  final String model;
  final String mac;
  var permissionManager = Get.find<IPermissionManager>();

  @override
  void onInit() {
    getPermission();
    loadListeners();
    connect();
    super.onInit();
  }

  @protected
  T createWorker();

  @override
  void dispose() {
    disconnect();
    releaseListeners();
    super.dispose();
  }

  @protected
  @mustCallSuper
  void loadListeners() {
    worker.connectErrorEvent.addListener(_onConnectFail);
    worker.connectedEvent.addListener(_onConnectSuccess);
    worker.disconnectedEvent.addListener(_onDisconnected);
  }

  @protected
  void releaseListeners() {
    worker.connectErrorEvent.removeListener(_onConnectFail);
    worker.connectedEvent.removeListener(_onConnectSuccess);
    worker.disconnectedEvent.removeListener(_onDisconnected);
  }

  Future<void> connect() async {
    await worker.connect();
  }

  Future<void> disconnect() async {
    await worker.disconnect();
    // 处理设备关闭成功事件
  }

  Future<void> getPermission() async {
    await permissionManager.requestLocationPermission();
    await permissionManager.requestBluetoothConnectPermission();
    await permissionManager.requestBluetoothAdvertisePermission();
    await permissionManager.requestBluetoothScanPermission();
  }

  void _onConnectFail(_, dynamic error) {
    connectStatus = WorkerStatus.connectionFailed;
    // 处理连接失败事件
  }

  void _onConnectSuccess(_, dynamic data) {
    connectStatus = WorkerStatus.connected;
    // 处理连接成功事件
  }

  void _onDisconnected(_, dynamic error) {
    connectStatus = WorkerStatus.disconnected;
    // 处理连接中断事件
  }
}
