using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using PhoenixLib.Logging;
using WingsAPI.Packets.Handling;
using WingsAPI.Plugins;
using WingsEmu.Game._packetHandling;
using WingsEmu.Packets;

namespace WingsEmu.Plugins.PacketHandling;

public class GamePacketHandlersGamePlugin : IGamePlugin
{
    private readonly IServiceProvider _container;
    private readonly IPacketHandlerContainer<IGamePacketHandler> _handlers;

    public GamePacketHandlersGamePlugin(IPacketHandlerContainer<IGamePacketHandler> handlers, IServiceProvider container)
    {
        _handlers = handlers;
        _container = container;
    }

    public string Name => nameof(GamePacketHandlersGamePlugin);

    public void OnLoad()
    {
        foreach (RegisteredPacketHandler registeredPacketHandler in _container.GetServices<RegisteredPacketHandler>())
        {
            try
            {
                Type handlerType = registeredPacketHandler.HandlerType;
                object tmp = _container.GetService(handlerType);
                if (!(tmp is IGamePacketHandler handler))
                {
                    continue;
                }

                Type baseType = handlerType.BaseType;
                if (baseType == null || !baseType.IsGenericType || baseType.GenericTypeArguments.Length == 0)
                {
                    Log.Warn($"[GAME_HANDLERS][SKIP_INVALID_BASE] {handlerType.FullName}");
                    continue;
                }

                Type type = baseType.GenericTypeArguments[0];
                if (type == null)
                {
                    Log.Warn($"[GAME_HANDLERS][SKIP_NULL_PACKET_TYPE] {handlerType.FullName}");
                    continue;
                }

                _handlers.Register(type, handler);
                string identification = type.GetCustomAttribute<PacketHeaderAttribute>()?.Identification ?? type.Name;
                Log.Info($"[GAME_HANDLERS][ADD_HANDLER] {identification}");
            }
            catch (Exception e)
            {
                Log.Error($"[GAME_HANDLERS][FAIL_ADD] HandlerType={registeredPacketHandler?.HandlerType?.FullName}", e);
                // ignored
            }
        }
    }
}