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

namespace RimWorld
{

public class IncidentWorker_RefugeePodCrash : IncidentWorker
{
	protected override bool TryExecuteWorker( IncidentParms parms )
	{
		var map = (Map)parms.target;

		var contents = ItemCollectionGeneratorDefOf.RefugeePod.Worker.Generate(new ItemCollectionGeneratorParams());
		var dropSpot = DropCellFinder.RandomDropSpot(map);
		var refugee = FindPawn(contents);

		string letterTitle = "LetterLabelRefugeePodCrash".Translate();
		string letterText = "RefugeePodCrash".Translate();
		PawnRelationUtility.TryAppendRelationsWithColonistsInfo(ref letterText, ref letterTitle, refugee);
		Find.LetterStack.ReceiveLetter(letterTitle, letterText, LetterDefOf.NeutralEvent, new TargetInfo(dropSpot, map));

		var podInfo = new ActiveDropPodInfo();
		podInfo.innerContainer.TryAddRangeOrTransfer(contents);
		podInfo.openDelay = 180;
		podInfo.leaveSlag = true;
		DropPodUtility.MakeDropPodAt( dropSpot, map, podInfo, explode: true );	

		return true;
	}

	private Pawn FindPawn(List<Thing> things)
	{
		for( int i = 0; i < things.Count; i++ )
		{
			var p = things[i] as Pawn;

			if( p != null )
				return p;

			var c = things[i] as Corpse;

			if( c != null )
				return c.InnerPawn;
		}

		return null;
	}
}

}
