using System.Reflection;

using HarmonyLib;
using RobocraftX.Common;
using RobocraftX.UECS;
using Svelto.ECS;
using Unity.Entities;

using GamecraftModdingAPI.Engines;
using GamecraftModdingAPI.Utility;

namespace GamecraftModdingAPI.Blocks
{
    public class ScalingEngine : IApiEngine
    {
        private static IReactOnAddAndRemove<UECSPhysicsEntityCreationStruct> physicsEngine;

        public void Ready()
        {
        }

        public EntitiesDB entitiesDB { get; set; }
        public void Dispose()
        {
        }

        public string Name { get; } = "GamecraftModdingAPIScalingEngine";
        public bool isRemovable { get; } = false;
        
        private EntityManager _entityManager; //Unity entity manager

		public void UpdateCollision(EGID egid)
		{
			if (_entityManager == default)
				_entityManager = FullGameFields._physicsWorld.EntityManager;
			//Assuming the block exists
			var entity = entitiesDB.QueryEntity<UECSPhysicsEntityStruct>(egid).uecsEntity;
			var pes = new UECSPhysicsEntityCreationStruct();
			physicsEngine.Add(ref pes, egid); //Create new UECS entity
			_entityManager.DestroyEntity(entity);
		}

		[HarmonyPatch]
        public class PhysicsEnginePatch
        {
            static void Postfix(IReactOnAddAndRemove<UECSPhysicsEntityCreationStruct> __instance)
            {
                physicsEngine = __instance;
                Logging.MetaDebugLog("Physics engine injected.");
            }

            static MethodBase TargetMethod(Harmony instance)
            {
	            return AccessTools.Method("RobocraftX.StateSync.HandleUECSPhysicEntitiesWithPrefabCreationEngine" +
	                                      ":Ready");
            }
        }
    }
}