using System;
using System.Linq;
using Plugin.BLE.Abstractions;
using Plugin.BLE.Abstractions.Contracts;

namespace InABox.Avalonia.Platform.iOS;

public class iOS_BluetoothDevice(IDevice native) : IBluetoothDevice
{
    public void Dispose()
    {
        Native.Dispose();
    }

    public IDevice Native { get; } = native;

    public string ID => Native.Id.ToString();
    public string Name => Native.Name;

        
    private Guid GuidFromDisplayOrderBytes(byte[] displayBytes)
    {
        if (displayBytes == null || displayBytes.Length != 16)
            throw new ArgumentException("Byte array must be exactly 16 bytes.", nameof(displayBytes));

        return new Guid(new byte[]
        {
            // Data1 (4 bytes, little-endian)
            displayBytes[3], displayBytes[2], displayBytes[1], displayBytes[0],

            // Data2 (2 bytes, little-endian)
            displayBytes[5], displayBytes[4],

            // Data3 (2 bytes, little-endian)
            displayBytes[7], displayBytes[6],

            // Data4 (8 bytes, as-is)
            displayBytes[8], displayBytes[9], displayBytes[10], displayBytes[11],
            displayBytes[12], displayBytes[13], displayBytes[14], displayBytes[15]
        });
    }

    
    public Guid[] AvailableServices => Native.AdvertisementRecords
        .Where(x => x.Type == AdvertisementRecordType.UuidsComplete128Bit)
        .Select(x => GuidFromDisplayOrderBytes(x.Data))
        .ToArray();

    public DateTime LastSeen { get; set; }
    public byte[]? ManufacturerData { get; set; }
}