import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:seos_mobile_keys_plugin/app_usage_api.dart';
import 'package:seos_mobile_keys_plugin/seos_mobile_keys_plugin.dart';

class KeyRepository {
  final SeosMobileKeysPlugin _seosMobileKeysPlugin;
  bool _isScanning = false;

  KeyRepository(this._seosMobileKeysPlugin);

  Future<void> checkDeviceInfo() async {
    try {
      if (Platform.isAndroid) {
        final deviceInfo = DeviceInfoPlugin();
        final androidInfo = await deviceInfo.androidInfo;
        if (androidInfo.version.sdkInt >= 33) {
          await Permission.bluetoothScan.request();
          await Permission.bluetoothConnect.onGrantedCallback(() async {
            await _checkAndStartScan();
          }).request();
          await Permission.bluetoothAdvertise.request();
          await Permission.notification.request();
        } else if (androidInfo.version.sdkInt >= 31) {
          await Permission.bluetoothScan.request();
          await Permission.bluetoothConnect.onGrantedCallback(() async {
            await _checkAndStartScan();
          }).request();
          await Permission.bluetoothAdvertise.request();
        } else {
          await Permission.location.onGrantedCallback(() async {
            await _checkAndStartScan();
          }).request();
        }
      } else {
        await _checkAndStartScan();
      }
    } catch (e) {
      throw Exception('Failed to refresh keys - ${e.toString()}');
    }
  }

  Future<void> _checkAndStartScan() async {
    if (!_isScanning) {
      await startScanning();
      _isScanning = true;
    }
  }

  Future<void> stopScanning() async {
    try {
      await _seosMobileKeysPlugin.stopReaderScan();
      _isScanning = false;
    } catch (e) {
      throw Exception('Failed to stop scanning - ${e.toString()}');
    }
  }

  Future<void> startScanning() async {
    try {
      final openingTypes = [
        MobileKeysOpeningType(openingType: OpeningType.proximity),
        MobileKeysOpeningType(openingType: OpeningType.applicationSpecific),
        MobileKeysOpeningType(openingType: OpeningType.seamless),
      ];
      final lockServiceCodes = [
        1,
        2,
      ];
      await _seosMobileKeysPlugin.startReaderScan(
        MobileKeysScanMode.optimizePerformance,
        openingTypes,
        lockServiceCodes,
      );
      if (kDebugMode) {
        debugPrint('startScanning: "scanned');
      }
    } catch (e) {
      throw Exception('Failed to start scanning - ${e.toString()}');
    }
  }

  Future<void> openClosestReader() async {
    // try {
    await _seosMobileKeysPlugin.openClosestReader();
    // } catch (e) {
    //   throw Exception('Failed to open closest reader - ${e.toString()}');
    // }
  }

  Future<void> setRootOpeningTrigger() async {
    if (!Platform.isAndroid) return;
    try {
      await _seosMobileKeysPlugin.setRootOpeningTrigger();
    } catch (e) {
      // Do nothing
    }
  }

  Future<void> removeRootOpeningTrigger() async {
    if (!Platform.isAndroid) return;
    try {
      await _seosMobileKeysPlugin.removeRootOpeningTrigger();
    } catch (e) {
      // Do nothing
    }
  }
}