import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_zsdk/src/models/bluetooth_printer.dart';
import 'package:flutter_zsdk/src/models/flutter_zsdk_exception.dart';
import 'package:permission_handler/permission_handler.dart';

import 'flutter_zsdk_platform_interface.dart';

/// An implementation of [FlutterZsdkPlatform] that uses method channels.
class MethodChannelFlutterZsdk extends FlutterZsdkPlatform {
  static const bluetoothDiscoveryEventChannel = EventChannel('id.kalanusa.flutter_zsdk.channel_events/bluetooth_discovery');

  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('flutter_zsdk');

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<Stream<dynamic>> findBluetoothPrinters() async {
    // methodChannel.invokeMethod("findBluetoothPrinters");
    // final bluetoothPrinters = await methodChannel.invokeMethod<List<BluetoothPrinter>>('findBluetoothPrinters');
    // print(bluetoothPrinters);
    // return bluetoothPrinters ?? [];
    
    // StreamSubscription streamSubscription = bluetoothDiscoveryEventChannel.receiveBroadcastStream().listen((event) {
    //   print(event);
    // });
    if (!await FlutterBluePlus.isSupported) {
      throw FlutterZsdkException("Bluetooth is not supported on this device.");
    }


    if (await FlutterBluePlus.adapterState.first != BluetoothAdapterState.on) {
      if (Platform.isAndroid) {
        try {
          await FlutterBluePlus.turnOn();
        } on FlutterBluePlusException catch (e) {
          throw FlutterZsdkException("Failed to turn on bluetooth: ${e.description}");
        }
      } else {
        throw FlutterZsdkException("Bluetooth is not turned on on this device.");
      }
    }

    var bluetoothPermissionStatus = await Permission.bluetooth.status;
    var bluetoothConnectPermissionStatus = await Permission.bluetoothConnect.status;
    var bluetoothScanPermissionStatus = await Permission.bluetoothScan.status;
    var locationPermissionStatus = await Permission.location.status;

    if (!bluetoothPermissionStatus.isGranted || !bluetoothConnectPermissionStatus.isGranted || !bluetoothScanPermissionStatus.isGranted || !locationPermissionStatus.isGranted) {
      Map<Permission, PermissionStatus> permissionStatuses = await [
        Permission.bluetooth, 
        Permission.bluetoothConnect, 
        Permission.bluetoothScan, 
        Permission.location
      ].request();

      print(permissionStatuses[Permission.bluetooth]);
      print(permissionStatuses[Permission.bluetoothConnect]);
      print(permissionStatuses[Permission.bluetoothScan]);
      print(permissionStatuses[Permission.location]);

      if (permissionStatuses[Permission.bluetooth] == PermissionStatus.granted && permissionStatuses[Permission.bluetoothConnect] == PermissionStatus.granted && permissionStatuses[Permission.bluetoothScan] == PermissionStatus.granted && permissionStatuses[Permission.location] == PermissionStatus.granted) {
        return bluetoothDiscoveryEventChannel.receiveBroadcastStream();
      } else {
        // throw Exception("Permissions not granted, please allow permission to discover bluetooth printers.");
        throw FlutterZsdkException("Permissions not granted, please allow permission to discover bluetooth printers.");
      }

    } else {
        return bluetoothDiscoveryEventChannel.receiveBroadcastStream();
    }
    
  }
}
