using Autofac;
using InABox.Avalonia.Platform;
using InABox.Core;
using Exception = System.Exception;

namespace InABox.Avalonia.Platform;

public static class PlatformTools
{

    private static ContainerBuilder _builder = new ContainerBuilder();
    private static IContainer? _container;
    
    private static IDeviceId? _deviceId;
    public static IDeviceId DeviceId
    {
        get
        {
            _deviceId ??= Resolve<IDeviceId,DefaultDeviceId>();
            return _deviceId;
        }
    }
        
    private static IAppVersion? _appVersion;
    public static IAppVersion AppVersion
    {
        get
        {
            _appVersion ??= Resolve<IAppVersion, DefaultAppVersion>();
            return _appVersion;
        }
    }
        
    private static IImageTools? _imageTools;
    public static IImageTools ImageTools
    {
        get
        {
            _imageTools ??= Resolve<IImageTools, DefaultImageTools>();
            return _imageTools;
        }
    }
    
    private static IPdfRenderer? _pdfRenderer;
    public static IPdfRenderer PdfRenderer
    {
        get
        {
            _pdfRenderer ??= Resolve<IPdfRenderer, DefaultPdfRenderer>();
            return _pdfRenderer;
        }
    }
    
    public static Guid DigitalKeyServiceId = Guid.Parse("ce6c0b18-0000-1000-8000-00805F9B34FB");
    public static Guid DigitalKeyConfigId = Guid.Parse("447c1982-77ef-49be-a39a-2920f33c31e5");
    public static Guid DigitalKeyControlId = Guid.Parse("5b804487-b73f-406a-8240-649c23ad1590");
    public static double ScanTimeoutInSeconds = 15;
    
    private static IBluetooth? _bluetooth;
    public static IBluetooth Bluetooth
    {
        get
        {
            _bluetooth ??= Resolve<IBluetooth, DefaultBluetooth>();
            return _bluetooth;
        }
    }
    
    private static TInterface Resolve<TInterface, TDefault>() where TInterface : notnull, ILoggable where TDefault : TInterface, new() 
    {
        _container ??= _builder.Build();
        var result = _container.IsRegistered<TInterface>()
            ?_container.Resolve<TInterface>()
            : new TDefault();
        result.Logger = Logger.Main;
        return result;
    }

    public static void Register<TInterface, TImplementation>() 
        where TImplementation : TInterface
        where TInterface : notnull
    {
        _builder.RegisterType<TImplementation>().As<TInterface>();
    }
}