from bleak import BleakClient
import asyncio

#BLE_DISPLAY_CHARACTERISTIC_UUID = "19B10001-E8F2-537E-4F6C-D104768A1214"  # Example UUID

class BluetoothInterface:
    def __init__(self, address, characteristic_uuid):
        self.address = address
        self.char_uuid = characteristic_uuid
        self.client = BleakClient(address)

    """
    async def connect(self):
        if not self.client.is_connected:
            await self.client.connect()
    """

    async def send_payload_async(self, payload: str):
        try:
            if not self.client.is_connected:
                await self.client.connect()
            await self.client.write_gatt_char(self.char_uuid, payload.encode("utf-8"))
        except Exception as e:
            print(f"[BluetoothInterface] Error: {e}")
        """
        await self.connect()
        await self.client.write_gatt_char(BLE_DISPLAY_CHARACTERISTIC_UUID, payload.encode())
        """

    def send_payload(self, payload: str):
        asyncio.run(self.send_payload_async(payload))

    def is_connected(self):
        return self.client.is_connected if self.client else False
        
    def close(self):
        if self.client.is_connected:
            asyncio.run(self.client.disconnect())
        
        
        
    ###  This will be reworked a million times.  Make sure it gets looked at for speed, efficiency, and robustness.
    ###  These helpers will scale with the system in weird ways, so always think about scaling tradeoffs down the road.
