using System.Collections.Generic;
using Verse;
using RimWorld;
using rjw;
using Verse.AI;

namespace SCE
{
    public class JobDriver_LewdTameSex : JobDriver_SexBaseInitiatorSimple
    {
        private Pawn originalPartner;

        protected override IEnumerable<Toil> MakeNewToils()
        {
            originalPartner = Partner;
            if (SexAppraiser.would_fuck(pawn, Partner) > 0f)
            {
                foreach (var baseToil in base.MakeNewToils())
                {
                    yield return baseToil;
                }
            }

            if (originalPartner != Partner)
            {
                // Pawn got interrupted by another partner, then the original partner finished before them.
                yield break;
            }

            yield return Toils_Interpersonal.SetLastInteractTime(iTarget);

            Toil tryRecruit = Toils_Interpersonal.TryRecruit(iTarget);
            tryRecruit.FailOn(() => Map.designationManager.DesignationOn(Partner, DesignationDefOf.Tame) == null);
            yield return tryRecruit;

            Toil addTakeToPenWork = ToilMaker.MakeToil();
            addTakeToPenWork.initAction = delegate
            {
                if (AnimalPenUtility.NeedsToBeManagedByRope(Partner) && Partner.Faction == Faction.OfPlayer && AnimalPenUtility.GetCurrentPenOf(Partner, allowUnenclosedPens: false) == null)
                {
                    RopingPriority ropingPriority = RopingPriority.Closest;
                    string jobFailReason;
                    CompAnimalPenMarker penAnimalShouldBeTakenTo = AnimalPenUtility.GetPenAnimalShouldBeTakenTo(pawn, Partner, out jobFailReason, forced: false, canInteractWhileSleeping: true, allowUnenclosedPens: true, ignoreSkillRequirements: true, ropingPriority);
                    Job job = null;
                    if (penAnimalShouldBeTakenTo != null)
                    {
                        job = WorkGiver_TakeToPen.MakeJob(pawn, Partner, penAnimalShouldBeTakenTo, allowUnenclosedPens: true, ropingPriority, out jobFailReason);
                    }
                    if (job != null)
                    {
                        pawn.jobs.StartJob(job, JobCondition.Succeeded);
                    }
                    else
                    {
                        Messages.Message("MessageTameNoSuitablePens".Translate(Partner.Named("ANIMAL")), Partner, MessageTypeDefOf.NeutralEvent);
                    }
                }
            };
            addTakeToPenWork.defaultCompleteMode = ToilCompleteMode.Instant;
            yield return addTakeToPenWork;

        }
    }
}