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

namespace RimWorld
{

public class IncidentWorker_CropBlight : IncidentWorker
{
	//Constants
	private const float Radius = 16f;
	private const float BaseBlightChance = 0.1f;

	protected override bool CanFireNowSub(IIncidentTarget target)
	{
		Plant unused;

		return TryFindRandomBlightablePlant((Map)target, out unused);
	}

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

		if( !TryFindRandomBlightablePlant(map, out root) )
			return false;

		var rootRoom = root.GetRoom();
		root.CropBlighted();

		for( int i = 0, count = GenRadial.NumCellsInRadius(Radius); i < count; i++ )
		{
			var c = root.Position + GenRadial.RadialPattern[i];

			if( !c.InBounds(map) || c.GetRoom(map) != rootRoom )
				continue;

			var nextPlant = BlightUtility.GetFirstBlightableNowPlant(c, map);

			if( nextPlant == null || nextPlant == root )
				continue;

			if( Rand.Chance(BaseBlightChance * BlightChanceFactor(nextPlant.Position, root.Position)) )
				nextPlant.CropBlighted();
		}

		Find.LetterStack.ReceiveLetter("LetterLabelCropBlight".Translate(),
			"LetterCropBlight".Translate(),
			LetterDefOf.NegativeEvent,
			new TargetInfo(root.Position, map));

		return true;
	}

	private bool TryFindRandomBlightablePlant(Map map, out Plant plant)
	{
		Thing plantThing;

		bool found = map.listerThings.ThingsInGroup(ThingRequestGroup.Plant)
			.Where(x => ((Plant)x).BlightableNow)
			.TryRandomElement(out plantThing);

		plant = (Plant)plantThing;

		return found;
	}

	private float BlightChanceFactor(IntVec3 c, IntVec3 root)
	{
		return Mathf.InverseLerp(Radius, Radius / 2f, c.DistanceTo(root));
	}
}

}
