using adas_core.Domain.Exceptions;

namespace adas_core.Infrastructure.Utils;

public static class TypesUtils
{
    public static Type GetDriver(string deviceType, string device)
    {
        return deviceType switch
        {
            "Relay" => GetType("adas-core.module.Relays", device, deviceType),
            "LightBeacon" => GetType("adas-core.module.LightBeacons", device, deviceType),
            _ => throw new AdasException($"Device type {deviceType} not found")
        };
    }

    private static Type GetType(string typeName, string device, string deviceType)
    {
        var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
        var assembly = loadedAssemblies.FirstOrDefault(a =>
        {
            var name = a.GetName().Name;
            return name != null && name.Contains(typeName);
        });

        if (assembly == null)
            // El ensamblado no está cargado. Lanzar excepción o manejar el fallo.
            throw new AdasException($"Assembly '{typeName}' not loaded.");

        var fullClassName = $"{typeName.Replace('-', '_')}.Devices.{device}{deviceType}";

        var type = assembly.GetType(fullClassName,
            true,
            true);

        if (type != null) return type;

        throw new AdasException($"{typeName} driver not found");
    }
}