using System.Collections.Generic;
using System.Linq;
using Verse;
using RimWorld;
using HarmonyLib;

namespace SCE.Patches
{
    [HarmonyPatch]
    public class IncestPatches
    {
        [HarmonyPatch(typeof(LovePartnerRelationUtility), "IncestOpinionOffsetFor")]
        [HarmonyPostfix]
        static void IncestOpinionPreceptCorrection(Pawn other, Pawn pawn, ref float __result)
        {
            if (__result >= 0 || pawn.Ideo == null)
            {
                return;
            }

            if (pawn.Ideo.HasPrecept(SCEPreceptDefOf.Incest_DontCare))
            {
                __result = 0;
                return;
            }

            if (pawn.Ideo.HasPrecept(SCEPreceptDefOf.Incest_FreeApproved))
            {
                __result *= -0.2f;
                return;
            }
        }

        [HarmonyPatch(typeof(Pawn_RelationsTracker), "SecondaryRomanceChanceFactor")]
        [HarmonyPostfix]
        public static void IncestRomanceChancePreceptCorrection(Pawn ___pawn, Pawn otherPawn, ref float __result)
        {
            // If the pawn approves of incest, increase the result beyond what it would have been initially.
            // The bonus is additive in case the pawn is related to otherPawn in more than one way
            bool approvesOfIncest = ___pawn.Ideo?.HasPrecept(SCEPreceptDefOf.Incest_FreeApproved) ?? false;
            float approvalBonus = 1f;

            foreach (var relation in ___pawn.GetRelations(otherPawn).Where(rel => rel.familyByBloodRelation))
            {
                // Reverse default penalty
                __result /= relation.romanceChanceFactor;

                // Bonus if incest is approved
                if (approvesOfIncest)
                {
                    approvalBonus += 0.3f;
                }
            }

            __result *= approvalBonus;
        }
    }
}