import 'package:flutter/material.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:flutter_provisioning_for_iot/objects/bluetooth_object.dart';
import 'package:flutter_provisioning_for_iot/screens/bluetooth_device_settings.dart';

class BluetoothDeviceEntry extends ListTile {
  BluetoothDeviceEntry({
    super.key,
    required BuildContext context,
    required BluetoothDeviceSettings settingsPage,
    required BluetoothObject bluetoothObject,
    required BluetoothDevice device,
    GestureTapCallback? onTap,
    GestureLongPressCallback? onLongPress,
    bool enabled = true,
  }) : super(
          onTap: onTap,
          onLongPress: onLongPress,
          enabled: enabled,
          leading: Icon(bluetoothObject.isConnected ? Icons.bluetooth_connected : Icons.bluetooth),
          title: Text(bluetoothObject.name),
          subtitle: Text(bluetoothObject.address.toString()),
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              device.isBonded ? const Icon(Icons.link) : const SizedBox(width: 0, height: 0),
              Container(
                margin: const EdgeInsets.all(8.0),
                child: DefaultTextStyle(
                  style: _computeTextStyle(bluetoothObject.rssi),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Text(bluetoothObject.rssi.toString()),
                      const Text('dBm'),
                    ],
                  ),
                ),
              ),
              IconButton(
                  onPressed: () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (context) => settingsPage)); //const BluetoothDeviceEntry()));
                  },
                  icon: const Icon(Icons.settings)),
            ],
          ),
        );

  static TextStyle _computeTextStyle(int rssi) {
    /**/ if (rssi >= -35) {
      return TextStyle(color: Colors.greenAccent[700]);
    } else if (rssi >= -45) {
      return TextStyle(color: Color.lerp(Colors.greenAccent[700], Colors.lightGreen, -(rssi + 35) / 10));
    } else if (rssi >= -55) {
      return TextStyle(color: Color.lerp(Colors.lightGreen, Colors.lime[600], -(rssi + 45) / 10));
    } else if (rssi >= -65) {
      return TextStyle(color: Color.lerp(Colors.lime[600], Colors.amber, -(rssi + 55) / 10));
    } else if (rssi >= -75) {
      return TextStyle(color: Color.lerp(Colors.amber, Colors.deepOrangeAccent, -(rssi + 65) / 10));
    } else if (rssi >= -85) {
      return TextStyle(color: Color.lerp(Colors.deepOrangeAccent, Colors.redAccent, -(rssi + 75) / 10));
    } else {
      return const TextStyle(color: Colors.redAccent);
    }
  }
}
