using Verse;
using RimWorld;
using HarmonyLib;
using rjw;

namespace SCE.Patches
{
    [HarmonyPatch]
    public static class UserSettingsPatches
    {
        [HarmonyPatch(typeof(Dialog_ChooseMemes), "CanUseMeme")]
        [HarmonyPostfix]
        public static void HideDisabledMemes(MemeDef meme, ref bool __result)
        {
            __result = __result && IsMemeEnabled(meme);
        }

        // CanAdd for memes
        [HarmonyPatch(typeof(IdeoUtility), "CanAdd")]
        [HarmonyPostfix]
        public static void PreventDisabledMemeGeneration(MemeDef meme, ref bool __result)
        {
            __result = __result && IsMemeEnabled(meme);
        }

        // CanAdd for precepts
        [HarmonyPatch(typeof(IdeoFoundation), "CanAdd")]
        [HarmonyPostfix]
        public static void BlockDisabledPrecepts(IdeoFoundation __instance, PreceptDef precept, ref AcceptanceReport __result)
        {
            if (!IsPreceptEnabled(__instance.ideo, precept))
            {
                // Blank AcceptanceReport to hide from the UI.
                __result = false;
            }
        }

        private static bool IsMemeEnabled(MemeDef meme, Faction faction = null)
        {
            if (IdeoUIUtility.devEditMode)
            {
                return true;
            }
            // Always return true if the player already has this meme so that it can be removed
            if (faction?.ideos?.PrimaryIdeo.HasMeme(meme) ?? false)
            {
                return true;
            }

            if (!RJWSettings.bestiality_enabled && meme == SCEMemeDefOf.Zoophilic)
            {
                return false;
            }
            else if (!RJWSettings.rape_enabled && meme == SCEMemeDefOf.RapeCulture)
            {
                return false;
            }

            return true;
        }
        
        private static bool IsPreceptEnabled(Ideo ideo, PreceptDef precept)
        {
            if (((!RJWSettings.bestiality_enabled && precept.issue == SCEIssueDefOf.Bestiality)
                    || (!RJWSettings.rape_enabled && precept.issue == SCEIssueDefOf.Rape))
                && !IdeoUIUtility.devEditMode && !ideo.HasPrecept(precept))
            {
                return false;
            }
            return true;
        }
    }
}