using RimWorld;
using Verse;

namespace ArachnaeSwarm
{
    public class CompDelayedTerrainSpawn : ThingComp
    {
        private CompProperties_DelayedTerrainSpawn Props => (CompProperties_DelayedTerrainSpawn)props;

        private int ticksToSpawn;
        private bool started;

        public override void PostSpawnSetup(bool respawningAfterLoad)
        {
            base.PostSpawnSetup(respawningAfterLoad);
            StartDelayedSpawn();
        }

        public override void CompTick()
        {
            base.CompTick();
            if (started)
            {
                ticksToSpawn--;
                if (ticksToSpawn <= 0)
                {
                    DoTerrainSpawn();
                }
            }
        }

        private void StartDelayedSpawn()
        {
            started = true;
            ticksToSpawn = Props.delayTicks;
        }

        private void DoTerrainSpawn()
        {
            if (parent.Destroyed)
            {
                return;
            }

            if (Props.terrainToSpawn != null)
            {
                foreach (IntVec3 current in GenRadial.RadialCellsAround(parent.Position, Props.spawnRadius, true))
                {
                    if (current.InBounds(parent.Map) && current.Walkable(parent.Map))
                    {
                        parent.Map.terrainGrid.SetTerrain(current, Props.terrainToSpawn);
                    }
                }
            }
        }
    }
}