using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Verse;
using Verse.AI;

namespace RimWorld
{
abstract class IncidentWorker_ShipPartCrash : IncidentWorker
{
    //Constants
    private const float ShipPointsFactor = 0.9f;
    private const int IncidentMinimumPoints = 300; //One centipede

    //Properties
    protected virtual int CountToSpawn { get { return 1; } }

	protected override bool CanFireNowSub(IIncidentTarget target)
	{
		var map = (Map)target;

        if (map.listerThings.ThingsOfDef(def.shipPart).Count > 0)
            return false;

        return true;
    }

    protected override bool TryExecuteWorker(IncidentParms parms)
	{
		var map = (Map)parms.target;

        int spawnedCount = 0;
        int countToSpawn = CountToSpawn;
        IntVec3 lastSpawnedLoc = IntVec3.Invalid;

		// All ships in a group have the same impact angle because that way it looks cooler
		float angle = Rand.Range(0, 360f);

        for (int i = 0; i < countToSpawn; ++i)
        {
			//Find cell
            IntVec3 center;
			if( !CellFinderLoose.TryFindSkyfallerCell(ThingDefOf.CrashedShipPartIncoming,
				map,
				out center,
				minDistToEdge: 14,
				allowRoofedCells: false,
				allowCellsWithItems: true,
				allowCellsWithBuildings: true,
				colonyReachable: true) )
			{
				break;
			}

			//Create a ship part
			var shipPart = (Building_CrashedShipPart)ThingMaker.MakeThing(def.shipPart);
			shipPart.SetFaction(Faction.OfMechanoids);
			shipPart.GetComp<CompSpawnerMechanoidsOnDamaged>().pointsLeft = Mathf.Max(parms.points * ShipPointsFactor, IncidentMinimumPoints);

			//Create a skyfaller
			var skyfaller = SkyfallerMaker.MakeSkyfaller(ThingDefOf.CrashedShipPartIncoming, shipPart);
			skyfaller.shrapnelDirection = angle;
			GenSpawn.Spawn(skyfaller, center, map);

            ++spawnedCount;
            lastSpawnedLoc = center;
        }

        if (spawnedCount > 0)
        {
            //Make letter
			SendStandardLetter(new TargetInfo(lastSpawnedLoc, map));
        }

        return spawnedCount > 0;
    }
}

}
