using Verse;
using Verse.AI;
using Verse.AI.Group;
using RimWorld;

namespace SCE
{
    public class JobGiver_GoToNthDutyFocus : JobGiver_GotoTravelDestination
    {
        public IntRange waitTicks = new IntRange(30, 80);

        public int focusIndex = 1;

		protected override Job TryGiveJob(Pawn pawn)
		{
			pawn.mindState.nextMoveOrderIsWait = !pawn.mindState.nextMoveOrderIsWait;
			if (pawn.mindState.nextMoveOrderIsWait && !exactCell)
			{
				Job waitJob = JobMaker.MakeJob(JobDefOf.Wait_Wander);
				waitJob.expiryInterval = waitTicks.RandomInRange;
				return waitJob;
			}

			IntVec3 cell = focusIndex switch
            {
                1   => pawn.mindState.duty.focus.Cell,
                2   => pawn.mindState.duty.focusSecond.Cell,
                3   => pawn.mindState.duty.focusThird.Cell,
                _   => IntVec3.Invalid
            };

            if (!cell.IsValid)
            {
                return null;
            }

			if (!pawn.CanReach(cell, PathEndMode.OnCell, PawnUtility.ResolveMaxDanger(pawn, maxDanger)))
			{
				return null;
			}
			if (exactCell && pawn.Position == cell)
			{
				if (!ritualTagOnArrival.NullOrEmpty())
				{
					(pawn.GetLord()?.LordJob as LordJob_Ritual)?.AddTagForPawn(pawn, ritualTagOnArrival);
				}
				return null;
			}
			IntVec3 intVec = cell;
			if (!exactCell)
			{
				intVec = CellFinder.RandomClosewalkCellNear(cell, pawn.Map, 6);
			}

			Job result = JobMaker.MakeJob(JobDefOf.Goto, intVec);
			result.locomotionUrgency = PawnUtility.ResolveLocomotion(pawn, locomotionUrgency);
		    result.expiryInterval = jobMaxDuration;
			result.ritualTag = ritualTagOnArrival;
			return result;
		}

        public override ThinkNode DeepCopy(bool resolve = true)
        {
            var result = (JobGiver_GoToNthDutyFocus) base.DeepCopy(resolve);
            result.waitTicks = waitTicks;
            result.focusIndex = focusIndex;
            return result;
        }
    }
}