import 'dart:developer';
import 'dart:math';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_zsdk/flutter_zsdk.dart';
import 'package:flutter_zsdk/src/models/flutter_zsdk_exception.dart';
import 'package:flutter_zsdk_example/models/bluetooth_printer.dart';

void main() {
  runApp(const MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isDiscovering = false;
  List<BluetoothPrinter> _discoveredBluetoothPrinters = [];
  String _platformVersion = 'Unknown';
  final _flutterZsdkPlugin = FlutterZsdk();

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion =
          await _flutterZsdkPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  StreamSubscription? _bluetoothPrinterSubscription;

  void showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message))
    );
  }

  Future<void> discoverBluetoothDevices() async {
    try {
      Stream<dynamic> stream = await _flutterZsdkPlugin.findBluetoothPrinters();
      _bluetoothPrinterSubscription = stream.listen((event) {
        print(event);

        if (event == 'SOS') {
          _isDiscovering = true;

        }

        if (event is List) {
          _discoveredBluetoothPrinters.clear();
          for (var printer in event) {
            BluetoothPrinter bluetoothPrinter = BluetoothPrinter.fromMap(printer);

            _discoveredBluetoothPrinters.add(bluetoothPrinter);
          }

        }

        if (event == 'EOS') {
          _isDiscovering = false;
          showSnackBar('Bluetooth discovery finished, found ${_discoveredBluetoothPrinters.length} printers');
          _bluetoothPrinterSubscription?.cancel();
        }

        setState(() {});
      });
    
    } on PlatformException catch (e) {
      inspect(e);
      showSnackBar(e.message.toString());

    } on FlutterZsdkException catch (e) { 
      inspect(e);
      showSnackBar(e.message);

    } catch (e) {
      inspect(e);
      showSnackBar('Unexpected error while discovering bluetooth printers');

    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Running on: $_platformVersion\n'),
            SizedBox(height: 20),
        
            ElevatedButton(
              child: Text(_isDiscovering ? 'Discovering bluetooth printers...' : 'Discover nearby bluetooth printers'),
              onPressed: _isDiscovering ? null : () async {
                discoverBluetoothDevices();
              },
            ),
            SizedBox(height: 20),

            for (var printer in _discoveredBluetoothPrinters) ... [
              Text(printer.friendlyName),
              Text(printer.macAddress),
              SizedBox(height: 10)
            ]
          ] 
          
        ),
      ),

    );
  }
}
