using System.Text;
using BluetoothLENet;

namespace InABox.Avalonia.Platform.Desktop;

public class Desktop_ConnectedBluetoothDevice : Desktop_BluetoothDevice, IConnectedBluetoothDevice
{
    public Desktop_ConnectedBluetoothDevice(BLEDevice device) : base(device)
    {
    }

    public async Task<bool> WriteBytesAsync(Guid serviceid, Guid characteristicid, byte[] data)
    {
        var service = Device?.Services.FirstOrDefault(x=>x.Native.Uuid == serviceid);
        if (service != null)
        {
            var characteristic = service.Characteristics.FirstOrDefault(x=>x.Native.Uuid == characteristicid);
            if (characteristic != null)
                return await characteristic.WriteAsync(data);
        }
        return false;
    }

    public async Task<bool> WriteStringAsync(Guid serviceid, Guid characteristicid, string data)
    {
        try
        {
            var encoded = Encoding.UTF8.GetBytes(data);
            var result = await WriteBytesAsync(serviceid, characteristicid, encoded);
            return result;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            return false;
        }
       
    }

    public async Task<byte[]?> ReadBytesAsync(Guid serviceid, Guid characteristicid)
    {
        var service = Device?.Services.FirstOrDefault(x=>x.Native?.Uuid == serviceid);
        if (service != null)
        {
            var characteristic = service.Characteristics.FirstOrDefault(x=>x.Native?.Uuid == characteristicid);
            if (characteristic != null)
                return await characteristic.ReadAsync();
        }
        return [];
    }
    
    public async Task<String?> ReadStringAsync(Guid serviceid, Guid characteristicid)
    {
        var data = await ReadBytesAsync(serviceid,characteristicid);
        return data != null ? Encoding.UTF8.GetString(data) : null;
    }
}