using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;

public partial class EntityFactory
{
    static T NewViewEntity<T>() where T : ViewEntity
    {
        GameObject go = new GameObject(typeof(T).Name);
        return go.AddComponent<T>();
    }

    private static Dictionary<int, Func<ViewEntity>> ViewEntityDict;

    static ViewEntity NewViewEntity(Type entityType)
    {
        GameObject go = new GameObject(entityType.Name);
        return (ViewEntity)go.AddComponent(entityType);
    }

    public static ViewEntity CreateEntity(int entityType)
    {
        if (ViewEntityDict == null)
        {
            var list = typeof(EntityFactory).Assembly.DefinedTypes
                .Where(x => x.IsSubclassOf(typeof(ViewEntity)))
                .Select(x => (Type: x, EntityType: x.GetCustomAttribute<EntityTypeAttribute>()))
                .Where(x => x.EntityType != null);

            ViewEntityDict = new Dictionary<int, Func<ViewEntity>>();
            
            foreach ((TypeInfo Type, EntityTypeAttribute EntityType) entityTypeTuple in list)
            {
                ViewEntityDict.Add(entityTypeTuple.EntityType.entityType, () =>  NewViewEntity(entityTypeTuple.Type) );
            }
                
            /*.ToDictionary(x => x.EntityType.entityType, x => (type)=>
            {
                return NewViewEntity(type);
            });*/
        }

        if (ViewEntityDict.ContainsKey(entityType))
        {
            return ViewEntityDict[entityType]();
        }
        else
        {
            GameDebug.LogError($"cannot create type :{entityType}");
            return null;
        }
    }
}