using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using SuperFantasyKingdom;
using SuperFantasyKingdom.UI;
using UnityEngine;
using UnityEngine.Localization;
using UnityEngine.UI;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("WeeklyHermit")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+aeee0721e5ef0b3fcf58a62a6b847c5f1168321f")]
[assembly: AssemblyProduct("WeeklyHermit")]
[assembly: AssemblyTitle("WeeklyHermit")]
[assembly: AssemblyVersion("0.1.0.0")]
namespace WeeklyHermit;
internal static class Checkpoint
{
[HarmonyPatch(typeof(GameDataManager), "Load")]
private static class Load
{
private static void Prefix(GameData ___m_GameData)
{
resolvedDay = ((___m_GameData != null && File.Exists(Marker(___m_GameData))) ? (___m_GameData.day + 1) : 0);
}
}
[HarmonyPatch(typeof(GameDataManager), "GenerateGameData")]
private static class Save
{
private static void Postfix(GameData __result)
{
if (__result == null || resolvedDay == 0 || __result.day + 1 != resolvedDay)
{
return;
}
try
{
string path = Marker(__result);
Directory.CreateDirectory(Path.GetDirectoryName(path));
using (File.Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
{
}
}
catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException)
{
Log.LogWarning((object)("Could not record the saved Hermit decision: " + ex.Message));
}
}
}
private static int resolvedDay;
internal static ManualLogSource Log;
internal static bool Resolved => resolvedDay == DaytimeManager.Instance.CurrentDay();
internal static void Resolve()
{
resolvedDay = DaytimeManager.Instance.CurrentDay();
}
private static string Marker(GameData data)
{
//IL_0029: Unknown result type (might be due to invalid IL or missing references)
string text = Helper.GenerateHash(string.Join("|", SettingsManager.Instance.GetProfile(), data.runID, data.kingdom, data.day, data.lastPlayed, data.hash));
return Path.Combine(Paths.ConfigPath, "WeeklyHermit", "checkpoints", text + ".done");
}
}
internal static class RecruitmentPool
{
internal static List<T> Read<T>(IEnumerable<string> unlocked, IEnumerable<string> banned, Func<string, T> lookup, Func<T, string> identifier, Func<string, bool> hermitAllows, Func<T, bool> merchantAllows) where T : class
{
HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
foreach (string item in banned)
{
if (!string.IsNullOrWhiteSpace(item))
{
hashSet.Add(item);
T val = lookup(item);
if (val != null)
{
hashSet.Add(identifier(val));
}
}
}
HashSet<string> hashSet2 = new HashSet<string>(StringComparer.Ordinal);
List<T> list = new List<T>();
foreach (string item2 in unlocked)
{
if (string.IsNullOrWhiteSpace(item2) || hashSet.Contains(item2))
{
continue;
}
T val2 = lookup(item2);
if (val2 == null)
{
continue;
}
string text = identifier(val2);
if (!string.IsNullOrWhiteSpace(text) && !hashSet.Contains(text) && !hashSet2.Contains(text))
{
if (text != item2)
{
val2 = lookup(text);
}
if (val2 != null && !(identifier(val2) != text) && hermitAllows(item2) && (!(text != item2) || hermitAllows(text)) && merchantAllows(val2))
{
hashSet2.Add(text);
list.Add(val2);
}
}
}
list.Sort((T left, T right) => StringComparer.Ordinal.Compare(identifier(left), identifier(right)));
return list;
}
}
internal sealed class MapHandoff
{
private int clearFrames;
internal bool CanOpen(bool mapAvailable, bool guestActive, bool overlayOpen, bool overlayMinimized)
{
if (!mapAvailable || guestActive || overlayOpen || overlayMinimized)
{
clearFrames = 0;
}
else
{
clearFrames++;
}
return clearFrames >= 2;
}
}
internal static class Schedule
{
internal static bool IsRepeat(int day, int interval, bool challenge)
{
if (!challenge && interval > 0 && day > 2)
{
return (day - 2) % interval == 0;
}
return false;
}
}
internal sealed class OfferDeck<T> where T : class
{
private readonly Random random;
private List<T> cards;
private int next;
internal OfferDeck(int runSeed, int day, List<T> candidates)
{
random = new Random((runSeed * 397) ^ day);
Shuffle(candidates);
}
internal void Shuffle(List<T> candidates)
{
cards = candidates;
next = 0;
for (int num = cards.Count - 1; num > 0; num--)
{
int index = random.Next(num + 1);
T value = cards[num];
cards[num] = cards[index];
cards[index] = value;
}
}
internal T Draw()
{
if (next >= cards.Count)
{
return null;
}
return cards[next++];
}
}
[BepInPlugin("gkj.superfantasykingdom.weeklyhermit", "Weekly Hermit", "0.1.0")]
public sealed class WeeklyHermitPlugin : BaseUnityPlugin
{
[HarmonyPatch(typeof(GuestHermit), "OnLoad")]
private static class HermitLoad
{
private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
Action<Object> action = Object.Destroy;
Action<Object> action2 = ReleaseOrQueue;
return Transpilers.MethodReplacer(instructions, (MethodBase)action.Method, (MethodBase)action2.Method);
}
private static void ReleaseOrQueue(Object target)
{
int day = DaytimeManager.Instance.CurrentDay();
GameManager instance = GameManager.Instance;
if (!((Object)(object)instance == (Object)(object)queuedScene) || !(target == (Object)(object)retainedGuest))
{
GameObject val = (GameObject)(object)((target is GameObject) ? target : null);
GuestHermit hermit = default(GuestHermit);
if (val != null && Schedule.IsRepeat(day, interval.Value, MainManager.Instance.IsChallenge()) && !Checkpoint.Resolved && (Object)(object)instance != (Object)(object)queuedScene && val.TryGetComponent<GuestHermit>(ref hermit))
{
queuedScene = instance;
retainedGuest = val;
val.SetActive(false);
((MonoBehaviour)instance).StartCoroutine(WaitForMap(instance, day, hermit));
}
else
{
Object.Destroy(target);
}
}
}
}
[HarmonyPatch(typeof(GuestHermit), "OnDialogOver")]
private static class NativeEncounter
{
private static bool Prefix(GuestHermit __instance, bool b)
{
if (EligibleUnits(__instance).Count != 0)
{
return true;
}
NativeDialogue.Complete((Guest)(object)__instance, b);
return false;
}
}
[HarmonyPatch]
private static class NativeDialogue
{
[MethodImpl(MethodImplOptions.NoInlining)]
[HarmonyReversePatch(/*Could not decode attribute arguments.*/)]
[HarmonyPatch(typeof(Guest), "OnDialogOver")]
internal static void Complete(Guest instance, bool b)
{
throw new NotSupportedException("Reverse patch was not installed.");
}
}
[HarmonyPatch(typeof(UIOverlayMerchant), "GenerateUnits")]
private static class NativeDraw
{
internal static HashSet<string> Allowed;
private static bool Prefix(Func<Unit> ___m_GetUnitCallback, bool reroll, out HashSet<string> __state)
{
__state = Allowed;
Allowed = null;
if (reroll)
{
object? obj = ___m_GetUnitCallback?.Target;
GuestHermit val = (GuestHermit)((obj is GuestHermit) ? obj : null);
if (val != null)
{
List<Unit> list = EligibleUnits(val);
if (list.Count == 0)
{
OverlayManager.Instance.CloseOverlay(false);
return false;
}
Allowed = new HashSet<string>(list.ConvertAll((Unit unit) => ((Entity)unit).GetEntityIdentifier()), StringComparer.Ordinal);
return true;
}
}
return true;
}
private static void Finalizer(HashSet<string> __state)
{
Allowed = __state;
}
}
[HarmonyPatch(typeof(GuestHermit), "CheckUnit")]
private static class NativeEligibility
{
private static bool Prefix(string __0)
{
if (string.IsNullOrWhiteSpace(__0))
{
return false;
}
if (NativeDraw.Allowed == null)
{
return true;
}
Unit unit = AddressablesManager.Instance.GetUnit(__0);
if (Object.op_Implicit((Object)(object)unit))
{
return NativeDraw.Allowed.Contains(((Entity)unit).GetEntityIdentifier());
}
return false;
}
}
[HarmonyPatch(typeof(UIOverlayMerchant), "Reroll", new Type[]
{
typeof(bool),
typeof(bool),
typeof(bool),
typeof(bool)
})]
private static class FinishReroll
{
private static void Postfix(UIOverlayMerchant __instance, int ___m_PossibleItemAmount)
{
if (MerchantCallback.Invoke(__instance) == new Action<int, ResourceAmount[]>(ResolveRecruitment))
{
__instance.SetPossibleItemAmount(___m_PossibleItemAmount);
}
}
}
[HarmonyPatch(typeof(UIOverlayMerchant), "AddBuyButton")]
private static class BindPurchase
{
private static void Postfix(UIOverlayMerchant __instance, UICard spawned, Transform __result)
{
if (spawned is UICardUnit && MerchantCallback.Invoke(__instance) == new Action<int, ResourceAmount[]>(ResolveRecruitment))
{
((Component)spawned).gameObject.AddComponent<RecruitPurchase>().Button = ((Component)__result).GetComponent<Button>();
}
}
}
[HarmonyPatch(typeof(UICardUnit), "Details")]
private static class InspectRecruit
{
private static void Postfix(UICardUnit __instance)
{
UIOverlayMerchant componentInParent = ((Component)__instance).GetComponentInParent<UIOverlayMerchant>(true);
if (Object.op_Implicit((Object)(object)componentInParent) && !((Component)__instance).gameObject.activeInHierarchy && MerchantCallback.Invoke(componentInParent) == new Action<int, ResourceAmount[]>(ResolveRecruitment))
{
inspectedCard = __instance;
}
}
}
[HarmonyPatch(typeof(OverlayManager), "ShowBackup")]
private static class ReturnToRecruit
{
private static void Postfix()
{
if (Object.op_Implicit((Object)(object)inspectedCard) && ((Component)inspectedCard).gameObject.activeInHierarchy)
{
RecruitPurchase component = ((Component)inspectedCard).GetComponent<RecruitPurchase>();
Button val = (Object.op_Implicit((Object)(object)component) ? component.Button : ((UICard)inspectedCard).GetCardButton());
if (Object.op_Implicit((Object)(object)val) && ((Behaviour)val).isActiveAndEnabled && ((Selectable)val).IsInteractable())
{
GamepadManager.Instance.SetGameObjectToSelect(((Component)val).gameObject, true);
}
}
inspectedCard = null;
}
}
private const string PluginId = "gkj.superfantasykingdom.weeklyhermit";
private Harmony harmony;
private static ConfigEntry<int> interval;
private static GameManager queuedScene;
private static GameObject retainedGuest;
private static readonly FieldRef<GuestHermit, LocalizedString> Title = AccessTools.FieldRefAccess<GuestHermit, LocalizedString>("stringTitle");
private static readonly FieldRef<GuestHermit, LocalizedString> Description = AccessTools.FieldRefAccess<GuestHermit, LocalizedString>("stringDesc");
private static readonly FieldRef<GuestHermit, LocalizedString> Decline = AccessTools.FieldRefAccess<GuestHermit, LocalizedString>("stringCancel");
private static readonly FieldRef<DialogueManager, DialogueBox> ActiveBox = AccessTools.FieldRefAccess<DialogueManager, DialogueBox>("dialogueBox");
private static readonly FieldRef<UIOverlayMerchant, Action<int, ResourceAmount[]>> MerchantCallback = AccessTools.FieldRefAccess<UIOverlayMerchant, Action<int, ResourceAmount[]>>("m_Callback");
private static UICardUnit inspectedCard;
private void Awake()
{
//IL_0026: Unknown result type (might be due to invalid IL or missing references)
//IL_0030: Expected O, but got Unknown
//IL_0046: Unknown result type (might be due to invalid IL or missing references)
//IL_0050: Expected O, but got Unknown
interval = ((BaseUnityPlugin)this).Config.Bind<int>("Schedule", "IntervalDays", 7, new ConfigDescription("Days between repeat visits after Day 2 in a standard run.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 365), Array.Empty<object>()));
Checkpoint.Log = ((BaseUnityPlugin)this).Logger;
harmony = new Harmony("gkj.superfantasykingdom.weeklyhermit");
harmony.PatchAll(typeof(WeeklyHermitPlugin).Assembly);
}
private void OnDestroy()
{
Harmony obj = harmony;
if (obj != null)
{
obj.UnpatchSelf();
}
queuedScene = null;
retainedGuest = null;
inspectedCard = null;
}
private static IEnumerator WaitForMap(GameManager scene, int day, GuestHermit hermit)
{
MapHandoff handoff = new MapHandoff();
WaitForEndOfFrame afterUpdates = new WaitForEndOfFrame();
bool mapAvailable;
OverlayManager instance2;
do
{
yield return afterUpdates;
if (!Object.op_Implicit((Object)(object)hermit) || scene.IsUnloading() || scene.IsGameOver() || DaytimeManager.Instance.CurrentDay() != day)
{
yield break;
}
DialogueManager instance = DialogueManager.Instance;
DialogueBox val = ActiveBox.Invoke(instance);
mapAvailable = scene.IsGameRunning() && !scene.IsForcedPause() && !GameCamera.Instance.IsCutscene() && !instance.IsInDialogue() && (!Object.op_Implicit((Object)(object)val) || !((Component)val).gameObject.activeInHierarchy) && UIManager.Instance.IsWorldInteractable();
instance2 = OverlayManager.Instance;
}
while (!handoff.CanOpen(mapAvailable, (Object)(object)WorldManager.Instance.GetGuest() != (Object)null, instance2.IsOpen(), instance2.HasMinimizedOverlay()));
Func<Unit, ResourceAmount[]> func = AccessTools.MethodDelegate<Func<Unit, ResourceAmount[]>>(AccessTools.DeclaredMethod(typeof(GuestHermit), "GetPrice", (Type[])null, (Type[])null), (object)hermit, true);
List<Unit> list = EligibleUnits(hermit);
if (list.Count != 0)
{
OfferDeck<Unit> deck = new OfferDeck<Unit>(scene.GetSeed(), day, list);
UIOverlayMerchant merchantScreen = OverlayManager.Instance.GetMerchantScreen();
merchantScreen.Init(Title.Invoke(hermit).GetLocalizedString());
merchantScreen.SetActor(((Guest)hermit).GetDialogueCollection().GetActor());
merchantScreen.SetText(Description.Invoke(hermit).GetLocalizedString());
merchantScreen.SetUseCardSelectCallback(true);
merchantScreen.SetCallback((Action<int, ResourceAmount[]>)ResolveRecruitment);
merchantScreen.CanBan(0, "", "", "");
merchantScreen.Units((Func<Unit>)deck.Draw, func, true, true);
merchantScreen.AllowReroll((Action<UIOverlayMerchant, bool>)null, (Action<UIOverlayMerchant>)delegate(UIOverlayMerchant merchant)
{
List<Unit> list2 = EligibleUnits(hermit);
deck.Shuffle(list2);
merchant.SetPossibleItemAmount(list2.Count);
}, 0);
merchantScreen.SetPossibleItemAmount(list.Count);
merchantScreen.SetCancel(Decline.Invoke(hermit).GetLocalizedString(), (Action<UIOverlayMerchant>)delegate
{
RaceDataManager.Instance.AddRaceEvent((RaceEvent)16);
Checkpoint.Resolve();
}, false);
merchantScreen.Display();
}
}
private static void ResolveRecruitment(int id, ResourceAmount[] costs)
{
Checkpoint.Resolve();
}
private static List<Unit> EligibleUnits(GuestHermit hermit)
{
//IL_0030: Unknown result type (might be due to invalid IL or missing references)
//IL_0035: Unknown result type (might be due to invalid IL or missing references)
Func<string, bool> hermitAllows = AccessTools.MethodDelegate<Func<string, bool>>(AccessTools.DeclaredMethod(typeof(GuestHermit), "CheckUnit", (Type[])null, (Type[])null), (object)hermit, true);
UnlockedUnitsManager instance = UnlockedUnitsManager.Instance;
Races race = RaceManager.Instance.GetRace();
return RecruitmentPool.Read(instance.GetUnlocked(), instance.GetBannedUnits(), delegate(string key)
{
Unit unit = AddressablesManager.Instance.GetUnit(key);
return (!Object.op_Implicit((Object)(object)unit)) ? null : unit;
}, (Unit unit) => ((Entity)unit).GetEntityIdentifier(), hermitAllows, (Unit unit) => ((Entity)unit).GetRace() != race && (int)((Entity)unit).GetRace() != 9 && UnitManager.Instance.CanAddUnit((UnitBase)(object)unit, false, false));
}
}
internal sealed class RecruitPurchase : MonoBehaviour
{
internal Button Button;
}