using System.Collections.Generic;
using Verse;
using RimWorld;
using Verse.AI;
using Verse.AI.Group;

namespace ArachnaeSwarm
{
    public class JobGiver_MaintainBuildings : JobGiver_AIFightEnemies
    {
        private bool onlyIfDamagingState;

        // 新增属性，用于存储可维护的ThingDef列表
        public List<ThingDef> maintainableThingDefs;

        private static readonly float CellsInScanRadius = GenRadial.NumCellsInRadius(7.9f);

        public override ThinkNode DeepCopy(bool resolve = true)
        {
            JobGiver_MaintainBuildings obj = (JobGiver_MaintainBuildings)base.DeepCopy(resolve);
            obj.onlyIfDamagingState = onlyIfDamagingState;
            obj.maintainableThingDefs = maintainableThingDefs; // 复制列表
            return obj;
        }

        protected override Job TryGiveJob(Pawn pawn)
        {
            Room room = pawn.GetRoom();
            for (int i = 0; (float)i < CellsInScanRadius; i++)
            {
                IntVec3 intVec = pawn.Position + GenRadial.RadialPattern[i];
                if (!intVec.InBounds(pawn.Map) || intVec.GetRoom(pawn.Map) != room)
                {
                    continue;
                }

                // 遍历可维护的ThingDef列表
                foreach (ThingDef thingDef in maintainableThingDefs)
                {
                    // 查找指定ThingDef的建筑
                    Thing targetThing = (Thing)pawn.Map.thingGrid.ThingAt(intVec, thingDef);

                    if (targetThing != null && pawn.CanReserve(targetThing))
                    {
                        CompMaintainable compMaintainable = targetThing.TryGetComp<CompMaintainable>();
                        if (compMaintainable != null && compMaintainable.CurStage != 0 && (!onlyIfDamagingState || compMaintainable.CurStage == MaintainableStage.Damaging))
                        {
                            return JobMaker.MakeJob(JobDefOf.Maintain, targetThing);
                        }
                    }
                }
            }
            return null;
        }
    }
}