import 'dart:async';
import 'dart:ffi';
import 'dart:typed_data';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

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

  @override
  State<ConnectionPage> createState() => _ConnectionPage();
}

void printDiscovered() {}

List<BluetoothDiscoveryResult> scanBluetoothDevice(
    List<BluetoothDiscoveryResult> results) {
  print("Scanning started!");
  FlutterBluetoothSerial.instance.startDiscovery().listen((r) {
    print(r.device.address);
    final existingIndex = results
        .indexWhere((element) => element.device.address == r.device.address);
    if (existingIndex >= 0)
      results[existingIndex] = r;
    else
      results.add(r);
  });

  return results;
}

class _ConnectionPage extends State<ConnectionPage> {
  late BluetoothConnection connection;
  bool _isConnected = false;
  var _latestDiscoveredId = "Nothing Yet";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Second Route'),
        backgroundColor: Colors.blueGrey,
      ),
      body: Column(
        children: [
          Center(
            child: ElevatedButton(
              onPressed: () {
                if (_isConnected && connection.isConnected) {
                  connection.close();
                  print('Connection Closed');
                  _isConnected = false;
                }
              },
              child: const Text('Disconnect Bluetooth'),
            ),
          ),
          Center(
            child: ElevatedButton(
              onPressed: () async {
                try {
                  connection =
                      await BluetoothConnection.toAddress("98:D3:11:FC:39:EC");
                  print('Connected to the device');
                  _isConnected = true;
                  connection.input!.listen((Uint8List data) {
                    print(data);
                  });
                } catch (ex) {
                  print(ex);
                }
              },
              child: const Text('Connect Bluetooth'),
            ),
          ),
          Center(
            child: ElevatedButton(
              onPressed: () {
                FlutterBluetoothSerial.instance
                    .getBondedDevices()
                    .then((List<BluetoothDevice> bondedDevices) {
                  _latestDiscoveredId = "";
                  for (var device in bondedDevices) {
                    print(device.address + " / " + device.name!);
                    setState(() {
                      _latestDiscoveredId +=
                          "\n" + device.address + " / " + device.name!;
                    });
                  }
                });
              },
              child: const Text('Select Bluetooth'),
            ),
          ),
          Text(
              //Show the latest found Bluetooth addr
              _latestDiscoveredId),
          Center(
            child: ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text('Go back!'),
            ),
          )
        ],
      ),
    );
  }
}
