Decompiled source of OneMoreDawn v0.1.5

plugins/OneMoreDawn.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Clickable;
using SuperFantasyKingdom.Spawner;
using SuperFantasyKingdom.UI;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Localization;
using UnityEngine.Localization.Components;
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("OneMoreDawn")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.5.0")]
[assembly: AssemblyInformationalVersion("0.1.5+14e70772a254e609b8afa536c638f063f817e5fa")]
[assembly: AssemblyProduct("OneMoreDawn")]
[assembly: AssemblyTitle("OneMoreDawn")]
[assembly: AssemblyVersion("0.1.5.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace OneMoreDawn
{
	[HarmonyPatch]
	internal static class BossChests
	{
		private sealed class Chest
		{
			internal bool Collected;
		}

		private static readonly ConditionalWeakTable<DropBossChest, Chest> WeeklyChests = new ConditionalWeakTable<DropBossChest, Chest>();

		private static MethodInfo preparePool;

		private static MethodInfo countRelics;

		internal static void Bind()
		{
			preparePool = typeof(DropBossChest).GetMethod("PreparePool", BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
			countRelics = typeof(DropBossChest).GetMethod("GetAmountOfUnits", BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
			if (preparePool?.ReturnType != typeof(void) || countRelics?.ReturnType != typeof(int))
			{
				throw new InvalidOperationException("The native boss chest pool methods changed.");
			}
		}

		[HarmonyPatch(typeof(BossSpawner), "End", new Type[] { })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> TrackWeeklyChests(IEnumerable<CodeInstruction> code)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			return NativeIL.InsertAfter(code, (CodeInstruction instruction) => instruction.operand is MethodInfo methodInfo && methodInfo.DeclaringType == typeof(Object) && methodInfo.Name == "Instantiate" && methodInfo.IsGenericMethod && methodInfo.GetGenericArguments()[0] == typeof(DropBossChest), new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(BossChests), "TrackChest", (Type[])null, (Type[])null)));
		}

		private static DropBossChest TrackChest(DropBossChest chest)
		{
			if (ExtendedDay.Weekly(ExtendedDay.Today))
			{
				WeeklyChests.GetOrCreateValue(chest);
			}
			return chest;
		}

		[HarmonyPatch(typeof(DropBossChest), "AfterDialogue", new Type[] { typeof(bool) })]
		[HarmonyPrefix]
		private static bool ResolveEmptyChest(DropBossChest __instance)
		{
			if (!WeeklyChests.TryGetValue(__instance, out var value))
			{
				return true;
			}
			if (value.Collected)
			{
				return false;
			}
			preparePool.Invoke(__instance, null);
			if ((int)countRelics.Invoke(__instance, null) > 0)
			{
				return true;
			}
			value.Collected = true;
			((ClickableSprite)__instance).SetNotActive();
			Object.Destroy((Object)(object)((Component)__instance).gameObject);
			WorldManager.Instance.OpenedChestToCollect();
			AlertManager.Instance.DisplayMessage("Boss chest", "No eligible relics remain.");
			return false;
		}
	}
	[HarmonyPatch]
	internal static class Bosses
	{
		[HarmonyPatch(typeof(DaytimeManager), "IsBossDay", new Type[] { })]
		[HarmonyPostfix]
		private static void ExtendBossDays(DaytimeManager __instance, ref bool __result)
		{
			__result |= ExtendedDay.Weekly(__instance.CurrentDay());
		}

		[HarmonyPatch(typeof(DaytimeManager), "IsNormalBossDay", new Type[] { })]
		[HarmonyPostfix]
		private static void ExtendNormalBossDays(DaytimeManager __instance, ref bool __result)
		{
			ExtendBossDays(__instance, ref __result);
		}

		[HarmonyPatch(typeof(DaytimeManager), "IsSpecialDay", new Type[] { })]
		[HarmonyPostfix]
		private static void ExtendSpecialDays(DaytimeManager __instance, ref bool __result)
		{
			ExtendBossDays(__instance, ref __result);
		}

		[HarmonyPatch(typeof(BossSpawner), "OnDayStart", new Type[] { typeof(int) })]
		[HarmonyPrefix]
		private static bool ReserveWeeklySlot(int __0)
		{
			DaytimeManager instance = DaytimeManager.Instance;
			if (__0 != instance.CurrentDay() || !ExtendedDay.Weekly(__0))
			{
				return true;
			}
			ExtendedDay extendedDay2;
			ExtendedDay extendedDay = (extendedDay2 = ExtendedDay.Get(instance));
			if (extendedDay2.Bosses == null)
			{
				extendedDay2.Bosses = new BossSequence<Boss>(Settings.BossCount(__0));
			}
			return extendedDay.Bosses.TryBegin();
		}

		[HarmonyPatch(typeof(BossSpawner), "SpawnBoss", new Type[] { typeof(int) })]
		[HarmonyPrefix]
		private static void SelectScheduledTier(ref int __0)
		{
			int today = ExtendedDay.Today;
			if (ExtendedDay.Weekly(today))
			{
				__0 = Progression.BossTier((today - 1) / 7, ExtendedDay.Current.Bosses.Finished);
			}
		}

		[HarmonyPatch(typeof(BossSpawner), "SpawnBoss", new Type[] { typeof(int) })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> TuneNativeBossLevel(IEnumerable<CodeInstruction> code)
		{
			return NativeIL.ReplaceCall(code, AccessTools.Method(typeof(Entity), "Init", new Type[2]
			{
				typeof(int),
				typeof(bool)
			}, (Type[])null), AccessTools.Method(typeof(Bosses), "InitializeBoss", (Type[])null, (Type[])null));
		}

		private static void InitializeBoss(Entity boss, int level, bool exists)
		{
			boss.Init(ExtendedDay.Weekly(ExtendedDay.Today) ? Progression.AdjustBossLevel(level, Settings.BossLevelOffset) : level, exists);
		}

		[HarmonyPatch(typeof(BossSpawner), "GetBoss", new Type[] { typeof(int) })]
		[HarmonyPrefix]
		private static void ForecastWeeklyTier(ref int __0)
		{
			if (__0 >= 4 && ExtendedDay.Later(ExtendedDay.Today))
			{
				__0 = Progression.BossTier(__0, 0);
			}
		}

		[HarmonyPatch(typeof(CombatManager), "BossSpawned", new Type[] { typeof(Boss) })]
		[HarmonyPrefix]
		private static void TrackActualBoss(Boss __0)
		{
			int today = ExtendedDay.Today;
			if (today == 29 && ExtendedDay.Campaign && ((MonsterBase)__0).IsFinalBoss())
			{
				ExtendedDay extendedDay = ExtendedDay.Get(DaytimeManager.Instance);
				if (extendedDay.Bosses == null)
				{
					extendedDay.Bosses = new BossSequence<Boss>(1);
					extendedDay.Bosses.TryBegin();
					extendedDay.Bosses.Spawned(__0);
				}
			}
			else if (ExtendedDay.Weekly(today))
			{
				BossSequence<Boss> bosses = ExtendedDay.Current.Bosses;
				bosses.Spawned(__0);
				Plugin.Log.LogInfo((object)$"Day {today}: boss {bosses.Finished + 1}/{bosses.Total} is {((Entity)__0).GetEntityIdentifier()}.");
			}
		}

		[HarmonyPatch(typeof(BossSpawner), "End", new Type[] { })]
		[HarmonyPostfix]
		private static void StartReinforcementsAfterIntro(Boss ___m_Boss)
		{
			if (Settings.ReinforcementsPercent != 0 && ExtendedDay.Weekly(ExtendedDay.Today) && !GameManager.Instance.IsGameOver())
			{
				ExtendedDay current = ExtendedDay.Current;
				if (current != null && current.Bosses?.TryStartReinforcements(___m_Boss) == true)
				{
					Waves.StartBossReinforcements(current);
				}
			}
		}

		[HarmonyPatch(typeof(CombatManager), "BossDeath", new Type[] { typeof(Boss) })]
		[HarmonyPrefix]
		private static bool StopFinaleOrReserveChest(Boss __0)
		{
			ExtendedDay current = ExtendedDay.Current;
			if (current?.Bosses == null)
			{
				return true;
			}
			if (current.Bosses.WasFinished(__0))
			{
				return false;
			}
			if (!current.Bosses.Owns(__0))
			{
				return true;
			}
			if (!current.Bosses.TryDefeat(__0))
			{
				return false;
			}
			if (ExtendedDay.Today == 29)
			{
				current.HordeStopped = true;
				Native.Remaining.SetValue(MonsterSpawner.Instance, 0);
				Plugin.Log.LogInfo((object)"Day 29: Ultimate Boss defeated. The horde has stopped.");
			}
			else
			{
				WorldManager.Instance.FoundChestToCollect();
			}
			return true;
		}

		[HarmonyPatch(typeof(CombatManager), "BossDeathAfter", new Type[] { typeof(Boss) })]
		[HarmonyPostfix]
		private static void FinishRewardPath(Boss __0)
		{
			ExtendedDay current = ExtendedDay.Current;
			if (current != null && current.Bosses?.FinishRewards(__0) == true && current.HordeStopped && !GameManager.Instance.IsGameOver())
			{
				DaytimeManager instance = DaytimeManager.Instance;
				Native.Overtime.SetValue(instance, false);
				instance.SkipTime();
			}
		}

		[HarmonyPatch(typeof(DaytimeManager), "Update", new Type[] { })]
		[HarmonyPrefix]
		private static void StartNextBoss(DaytimeManager __instance)
		{
			int num = __instance.CurrentDay();
			BossSequence<Boss> bossSequence = ExtendedDay.Find(__instance)?.Bosses;
			if (ExtendedDay.Weekly(num) && bossSequence != null && bossSequence.Ready && !Waves.HasBossReinforcements(bossSequence) && !GameManager.Instance.IsGameOver() && !WorldManager.Instance.HasChestToCollect() && CombatManager.Instance.CurrentMonstersAmount() <= 0 && !BossSpawner.Instance.IsBossDying() && !BossSpawner.Instance.IsInAnimation() && (__instance.IsDay() || __instance.IsSunset() || __instance.IsEvening()))
			{
				Native.StartBoss.Invoke(BossSpawner.Instance, new object[1] { num });
			}
		}
	}
	[HarmonyPatch]
	internal static class Calendar
	{
		private const string VisitorId = "sfk.visitorcalendar";

		internal static Action<UICalendar, int, GameObject> RebindPage { get; private set; }

		internal static bool CanBrowse { get; private set; } = true;

		internal static void BindVisitorCalendar(Harmony harmony)
		{
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Expected O, but got Unknown
			if (!Chainloader.PluginInfos.TryGetValue("sfk.visitorcalendar", out var value) || (Object)(object)value.Instance == (Object)null)
			{
				return;
			}
			Assembly assembly = ((object)value.Instance).GetType().Assembly;
			MethodInfo methodInfo = assembly.GetType("VisitorCalendar.CalendarPageApi")?.GetMethod("SetPage", BindingFlags.Static | BindingFlags.Public, null, new Type[3]
			{
				typeof(UICalendar),
				typeof(int),
				typeof(GameObject)
			}, null);
			RebindPage = ((methodInfo?.ReturnType == typeof(void)) ? ((Action<UICalendar, int, GameObject>)Delegate.CreateDelegate(typeof(Action<UICalendar, int, GameObject>), methodInfo, throwOnBindFailure: false)) : null);
			CanBrowse = RebindPage != null;
			if (!CanBrowse)
			{
				Plugin.Log.LogInfo((object)"Calendar paging requires Visitor Calendar 0.1.5 or later when Visitor Calendar is installed.");
			}
			Type type = assembly.GetType("VisitorCalendar.CalendarView");
			MethodInfo methodInfo2 = ((type == null) ? null : type.GetMethod("BindDay", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[2]
			{
				typeof(int),
				typeof(Transform)
			}, null));
			if (methodInfo2?.ReturnType != typeof(void))
			{
				Plugin.Log.LogWarning((object)"Visitor Calendar's day binder has changed. Extended appointment rendering is unavailable.");
				return;
			}
			try
			{
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(Calendar), "MapVisitorCell", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not connect Visitor Calendar to extended dates: " + ex.Message));
			}
		}

		private static bool MapVisitorCell(ref int __0)
		{
			int today = ExtendedDay.Today;
			if (!ExtendedDay.Later(today))
			{
				return true;
			}
			__0 = CalendarPage.DayForCell(today, __0);
			return __0 != 0;
		}

		[HarmonyPatch(typeof(UICalendar), "OnEnable", new Type[] { })]
		[HarmonyPostfix]
		[HarmonyBefore(new string[] { "sfk.visitorcalendar" })]
		private static void RenderExtendedPage(UICalendar __instance, Transform ___calendarDays, GameObject ___lastDay, TextMeshProUGUI ___textCycle, LocalizedString ___stringDayX, LocalizedString ___stringBoss)
		{
			int today = ExtendedDay.Today;
			if (ExtendedDay.Later(today))
			{
				(((Component)__instance).GetComponent<CalendarNavigation>() ?? ((Component)__instance).gameObject.AddComponent<CalendarNavigation>()).Open(__instance, ___calendarDays, ___lastDay, today, CanBrowse);
				long num = (long)today + (long)((7 - today % 7) % 7);
				((TMP_Text)___textCycle).text = ((TMP_Text)___textCycle).text + "  ·  " + ___stringDayX.GetLocalizedString(new object[1] { today.ToString() });
				if (num <= int.MaxValue)
				{
					int num2 = Settings.BossCount((int)num);
					((TMP_Text)___textCycle).text = ((TMP_Text)___textCycle).text + $"  ·  {___stringBoss.GetLocalizedString()} ×{num2}" + " (" + ___stringDayX.GetLocalizedString(new object[1] { num.ToString() }) + ")";
				}
			}
		}

		[HarmonyPatch(typeof(UICalendar), "OnEnable", new Type[] { })]
		[HarmonyPostfix]
		[HarmonyAfter(new string[] { "sfk.visitorcalendar", "sfk.weeklycontracts" })]
		private static void FocusToday(UICalendar __instance)
		{
			((Component)__instance).GetComponent<CalendarNavigation>()?.Ready();
		}

		[HarmonyPatch(typeof(UICalendar), "OnEnterDay", new Type[] { typeof(int) })]
		[HarmonyPrefix]
		[HarmonyBefore(new string[] { "sfk.visitorcalendar" })]
		private static void MapNativeHover(UICalendar __instance, ref int __0)
		{
			CalendarNavigation component = ((Component)__instance).GetComponent<CalendarNavigation>();
			if ((Object)(object)component != (Object)null)
			{
				__0 = CalendarPage.DayForCell(component.FirstDay, __0);
			}
		}

		[HarmonyPatch(typeof(UICalendar), "OnEnterDay", new Type[] { typeof(int) })]
		[HarmonyPrefix]
		[HarmonyAfter(new string[] { "sfk.visitorcalendar" })]
		private static bool ShowExtendedTooltip(UICalendar __instance, bool __runOriginal, int __0, Transform ___calendarDays, LocalizedString ___stringDayX, LocalizedString ___stringBoss)
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if (!__runOriginal)
			{
				return false;
			}
			CalendarNavigation component = ((Component)__instance).GetComponent<CalendarNavigation>();
			if ((Object)(object)component == (Object)null || (__0 >= 1 && __0 <= 28))
			{
				return true;
			}
			int num = __0 - component.FirstDay;
			if (num < 0 || num >= ___calendarDays.childCount)
			{
				return false;
			}
			string text = ___stringDayX.GetLocalizedString(new object[1] { __0.ToString() });
			int num2 = Settings.BossCount(__0);
			if (num2 > 0)
			{
				text += $"\n{___stringBoss.GetLocalizedString()} ×{num2}";
			}
			TooltipManager.Instance.SetAnchor((AnchorPresets)1);
			TooltipManager.Instance.Display(text, ___calendarDays.GetChild(num).position, true);
			return false;
		}
	}
	internal sealed class CalendarNavigation : MonoBehaviour
	{
		private const int WeekLength = 7;

		private UICalendar calendar;

		private Transform grid;

		private bool[] nativeArt;

		private int today;

		private RectTransform footer;

		private TextMeshProUGUI range;

		private Button previous;

		private Button next;

		internal int FirstDay { get; private set; }

		internal void Open(UICalendar overlay, Transform cells, GameObject finalDay, int day, bool canBrowse)
		{
			calendar = overlay;
			grid = cells;
			today = day;
			if (nativeArt == null)
			{
				nativeArt = new bool[Math.Min(grid.childCount, 28)];
				for (int i = 0; i < nativeArt.Length; i++)
				{
					bool[] array = nativeArt;
					int num = i;
					Transform obj = grid.GetChild(i).Find("Image");
					array[num] = obj != null && ((Component)obj).gameObject.activeSelf;
				}
			}
			finalDay.SetActive(false);
			FirstDay = CalendarPage.FirstDay(today);
			if (canBrowse && (Object)(object)footer == (Object)null)
			{
				CreateFooter();
			}
			DrawPage();
		}

		internal void Ready()
		{
			Calendar.RebindPage?.Invoke(calendar, FirstDay, ((Object)(object)footer != (Object)null) ? ((Component)footer).gameObject : null);
			Focus(((Component)grid.GetChild(today - FirstDay)).gameObject);
		}

		private void ChangePage(int direction, Button pressed)
		{
			int num = CalendarPage.Shift(FirstDay, direction);
			if (num != FirstDay)
			{
				TooltipManager.Instance.Hide();
				FirstDay = num;
				DrawPage();
				Calendar.RebindPage?.Invoke(calendar, FirstDay, ((Component)footer).gameObject);
				Focus(((Component)(((Selectable)pressed).IsInteractable() ? pressed : ((direction < 0) ? next : previous))).gameObject);
			}
		}

		private void DrawPage()
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < nativeArt.Length; i++)
			{
				Transform child = grid.GetChild(i);
				int num = CalendarPage.DayForCell(FirstDay, i + 1);
				((Component)child).gameObject.SetActive(num != 0);
				if (num != 0)
				{
					TextMeshProUGUI component = ((Component)child.Find("Day")).GetComponent<TextMeshProUGUI>();
					((TMP_Text)component).text = num.ToString();
					((Graphic)component).color = ((num == today) ? Color.yellow : ((num % 7 == 0) ? Color.red : Color.white));
					Transform obj = child.Find("Image");
					if (obj != null)
					{
						((Component)obj).gameObject.SetActive(FirstDay == 1 && nativeArt[i]);
					}
				}
			}
			if (!((Object)(object)footer == (Object)null))
			{
				((TMP_Text)range).text = $"{FirstDay} - {CalendarPage.LastDay(FirstDay)}";
				((Selectable)previous).interactable = CalendarPage.Shift(FirstDay, -1) != FirstDay;
				((Selectable)next).interactable = CalendarPage.Shift(FirstDay, 1) != FirstDay;
				LinkFocus(CalendarPage.LastDay(FirstDay) - FirstDay + 1);
			}
		}

		private void LinkFocus(int count)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Invalid comparison between Unknown and I4
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			Button val = (((Selectable)previous).interactable ? previous : next);
			Button val2 = (((Selectable)next).interactable ? next : previous);
			for (int i = 0; i < count; i++)
			{
				Selectable obj = Cell(i);
				Navigation navigation = obj.navigation;
				int num = i % 7;
				((Navigation)(ref navigation)).selectOnUp = ((i >= 7) ? Cell(i - 7) : (((int)((Navigation)(ref navigation)).mode == 4) ? ((Navigation)(ref navigation)).selectOnUp : null));
				((Navigation)(ref navigation)).mode = (Mode)4;
				((Navigation)(ref navigation)).selectOnLeft = ((num > 0) ? Cell(i - 1) : null);
				((Navigation)(ref navigation)).selectOnRight = ((num < 6 && i + 1 < count) ? Cell(i + 1) : null);
				((Navigation)(ref navigation)).selectOnDown = (Selectable)((i + 7 < count) ? ((object)Cell(i + 7)) : ((object)((num < 3) ? val : val2)));
				obj.navigation = navigation;
			}
			int index = count - 1 - (count - 1) % 7;
			Button obj2 = previous;
			Navigation navigation2 = default(Navigation);
			((Navigation)(ref navigation2)).mode = (Mode)4;
			((Navigation)(ref navigation2)).selectOnUp = Cell(index);
			((Navigation)(ref navigation2)).selectOnRight = (Selectable)(object)(((Selectable)next).interactable ? next : null);
			((Selectable)obj2).navigation = navigation2;
			Button obj3 = next;
			navigation2 = default(Navigation);
			((Navigation)(ref navigation2)).mode = (Mode)4;
			((Navigation)(ref navigation2)).selectOnUp = Cell(count - 1);
			((Navigation)(ref navigation2)).selectOnLeft = (Selectable)(object)(((Selectable)previous).interactable ? previous : null);
			((Selectable)obj3).navigation = navigation2;
			Selectable Cell(int num2)
			{
				return ((Component)grid.GetChild(num2)).GetComponent<Selectable>();
			}
		}

		private void CreateFooter()
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Expected O, but got Unknown
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Expected O, but got Unknown
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = Resources.Load<GameObject>("UI/OverlayMessage");
			object obj2;
			if (obj == null)
			{
				obj2 = null;
			}
			else
			{
				Transform obj3 = obj.transform.Find("Buttons/BuyButton");
				obj2 = ((obj3 != null) ? ((Component)obj3).GetComponent<Button>() : null);
			}
			Button val = (Button)obj2;
			if (!Object.op_Implicit((Object)(object)val))
			{
				Plugin.Log.LogWarning((object)"Calendar paging could not find the native menu button.");
				return;
			}
			GameObject val2 = new GameObject("Calendar pages", new Type[2]
			{
				typeof(RectTransform),
				typeof(LayoutElement)
			});
			footer = (RectTransform)val2.transform;
			((Transform)footer).SetParent(grid.parent, false);
			((Transform)footer).SetSiblingIndex(grid.GetSiblingIndex() + 1);
			footer.sizeDelta = new Vector2(436f, 40f);
			LayoutElement component = val2.GetComponent<LayoutElement>();
			component.preferredWidth = footer.sizeDelta.x;
			component.preferredHeight = footer.sizeDelta.y;
			previous = MakeButton(val, "Previous", -153f);
			next = MakeButton(val, "Next", 153f);
			((UnityEvent)previous.onClick).AddListener((UnityAction)delegate
			{
				ChangePage(-1, previous);
			});
			((UnityEvent)next.onClick).AddListener((UnityAction)delegate
			{
				ChangePage(1, next);
			});
			GameObject val3 = new GameObject("Date range", new Type[2]
			{
				typeof(RectTransform),
				typeof(TextMeshProUGUI)
			});
			RectTransform val4 = (RectTransform)val3.transform;
			((Transform)val4).SetParent((Transform)(object)footer, false);
			Vector2 val5 = default(Vector2);
			((Vector2)(ref val5))..ctor(0.5f, 0.5f);
			val4.pivot = val5;
			Vector2 anchorMin = (val4.anchorMax = val5);
			val4.anchorMin = anchorMin;
			val4.sizeDelta = new Vector2(174f, 32f);
			range = val3.GetComponent<TextMeshProUGUI>();
			((TMP_Text)range).font = ((TMP_Text)((Component)grid.GetChild(0).Find("Day")).GetComponent<TextMeshProUGUI>()).font;
			((TMP_Text)range).alignment = (TextAlignmentOptions)514;
			((TMP_Text)range).enableAutoSizing = true;
			((TMP_Text)range).fontSizeMin = 14f;
			((TMP_Text)range).fontSizeMax = 27f;
			((Graphic)range).raycastTarget = false;
		}

		private Button MakeButton(Button template, string title, float x)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			Button val = Object.Instantiate<Button>(template, (Transform)(object)footer, false);
			((Object)val).name = title;
			foreach (Transform item in ((Component)val).transform)
			{
				Transform val2 = item;
				((Component)val2).gameObject.SetActive(((Object)val2).name == "Text");
			}
			RectTransform val3 = (RectTransform)((Component)val).transform;
			Vector2 val4 = default(Vector2);
			((Vector2)(ref val4))..ctor(0.5f, 0.5f);
			val3.pivot = val4;
			Vector2 anchorMin = (val3.anchorMax = val4);
			val3.anchorMin = anchorMin;
			val3.sizeDelta = new Vector2(118f, 32f);
			val3.anchoredPosition = new Vector2(x, 0f);
			TextMeshProUGUI componentInChildren = ((Component)val).GetComponentInChildren<TextMeshProUGUI>();
			LocalizeStringEvent component = ((Component)componentInChildren).GetComponent<LocalizeStringEvent>();
			if (Object.op_Implicit((Object)(object)component))
			{
				((Behaviour)component).enabled = false;
			}
			((TMP_Text)componentInChildren).text = title;
			val.onClick = new ButtonClickedEvent();
			Navigation navigation = default(Navigation);
			((Navigation)(ref navigation)).mode = (Mode)3;
			((Selectable)val).navigation = navigation;
			return val;
		}

		private static void Focus(GameObject target)
		{
			GamepadManager.Instance.SetGameObjectToSelect(target, true);
			if (!target.activeInHierarchy)
			{
				return;
			}
			EventSystem current = EventSystem.current;
			if ((Object)(object)((current != null) ? current.currentSelectedGameObject : null) != (Object)(object)target)
			{
				EventSystem current2 = EventSystem.current;
				if (current2 != null)
				{
					current2.SetSelectedGameObject(target);
				}
			}
		}
	}
	internal static class CalendarPage
	{
		internal const int Length = 28;

		internal static int FirstDay(int today)
		{
			return today - (today - 1) % 28;
		}

		internal static int LastDay(int first)
		{
			return (int)Math.Min((long)first + 28L - 1, 2147483647L);
		}

		internal static int Shift(int first, int direction)
		{
			long num = (long)first + (long)(28 * direction);
			if (num < 1 || num > int.MaxValue)
			{
				return first;
			}
			return (int)num;
		}

		internal static int DayForCell(int today, int cell)
		{
			if (cell < 1 || cell > 28)
			{
				return 0;
			}
			long num = (long)FirstDay(today) + (long)cell - 1;
			if (num > int.MaxValue)
			{
				return 0;
			}
			return (int)num;
		}
	}
	internal sealed class ExtendedDay
	{
		private static readonly ConditionalWeakTable<DaytimeManager, ExtendedDay> Scenes = new ConditionalWeakTable<DaytimeManager, ExtendedDay>();

		internal BossSequence<Boss> Bosses;

		internal bool HordeStopped;

		internal bool CombatEnded;

		internal bool SettlementStarted;

		internal bool PreparingBossWave;

		internal static bool Campaign
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Invalid comparison between Unknown and I4
				if ((Object)(object)MainManager.Instance != (Object)null && !MainManager.Instance.IsChallenge() && (Object)(object)RaceManager.Instance != (Object)null)
				{
					if ((int)RaceManager.Instance.GetRace() != 0)
					{
						return (int)RaceManager.Instance.GetRace() == 2;
					}
					return true;
				}
				return false;
			}
		}

		internal static int Today
		{
			get
			{
				if (!((Object)(object)DaytimeManager.Instance != (Object)null))
				{
					return 0;
				}
				return DaytimeManager.Instance.CurrentDay();
			}
		}

		internal static ExtendedDay Current => Find(DaytimeManager.Instance);

		internal static bool Managed
		{
			get
			{
				if (!Later(Today))
				{
					return Current?.Bosses != null;
				}
				return true;
			}
		}

		internal static bool Stopped => Current?.HordeStopped ?? false;

		internal static bool Later(int day)
		{
			if (day > 29)
			{
				return Campaign;
			}
			return false;
		}

		internal static bool Weekly(int day)
		{
			if (Later(day))
			{
				return Progression.WeeklyBosses(day) > 0;
			}
			return false;
		}

		internal static ExtendedDay Get(DaytimeManager clock)
		{
			return Scenes.GetOrCreateValue(clock);
		}

		internal static ExtendedDay Find(DaytimeManager clock)
		{
			if ((Object)(object)clock != (Object)null && clock.CurrentDay() >= 29 && Campaign && Scenes.TryGetValue(clock, out var value))
			{
				return value;
			}
			return null;
		}

		internal static bool Pending(DaytimeManager clock)
		{
			int day = clock.CurrentDay();
			BossSequence<Boss> bossSequence = Find(clock)?.Bosses;
			if (bossSequence != null && !bossSequence.Complete)
			{
				return true;
			}
			if (!Later(day))
			{
				return false;
			}
			if (Weekly(day))
			{
				if (bossSequence != null)
				{
					return Waves.HasBossReinforcements(bossSequence);
				}
				return true;
			}
			MonsterSpawner instance = MonsterSpawner.Instance;
			if (Object.op_Implicit((Object)(object)instance))
			{
				return instance.GetMonstersToSpawn() > 0;
			}
			return false;
		}

		internal static bool CanSettle()
		{
			DaytimeManager instance = DaytimeManager.Instance;
			CombatManager instance2 = CombatManager.Instance;
			if (GameManager.Instance.IsGameRunning() && !GameManager.Instance.IsGameOver() && !Pending(instance) && instance2.IsCombatOver() && instance2.CurrentMonstersAmount() == 0 && !WorldManager.Instance.HasChestToCollect() && !ProvokedSpawner.Instance.IsProvoked())
			{
				return (Object)(object)CityManager.Instance.GetTavern() != (Object)null;
			}
			return false;
		}
	}
	internal static class NativeIL
	{
		internal static List<CodeInstruction> InsertAfter(IEnumerable<CodeInstruction> instructions, Func<CodeInstruction, bool> matches, params CodeInstruction[] additions)
		{
			List<CodeInstruction> list = instructions.ToList();
			int num = SingleSite(list, matches);
			list.InsertRange(num + 1, additions);
			return list;
		}

		internal static int SingleSite(List<CodeInstruction> code, Func<CodeInstruction, bool> matches)
		{
			int num = code.FindIndex((CodeInstruction instruction) => matches(instruction));
			if (num < 0 || code.FindIndex(num + 1, (CodeInstruction instruction) => matches(instruction)) >= 0)
			{
				throw new InvalidOperationException("Expected a unique native instruction.");
			}
			return num;
		}

		internal static IEnumerable<CodeInstruction> ReplaceCall(IEnumerable<CodeInstruction> instructions, MethodInfo original, MethodInfo replacement)
		{
			List<CodeInstruction> list = instructions.ToList();
			CodeInstruction obj = list[SingleSite(list, (CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, original))];
			obj.opcode = OpCodes.Call;
			obj.operand = replacement;
			return list;
		}
	}
	[BepInPlugin("gkj.onemoredawn", "One More Dawn", "0.1.5")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal const string Id = "gkj.onemoredawn";

		private const string Build = "0.8.070";

		private const string AssemblyHash = "B17E8A5530632393B24F582350366ED55475F34FFB197B0B394EA179480354C5";

		private Harmony patches;

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			try
			{
				using FileStream inputStream = File.OpenRead(typeof(DaytimeManager).Assembly.Location);
				using SHA256 sHA = SHA256.Create();
				string text = BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", "");
				if (Application.version != "0.8.070" || text != "B17E8A5530632393B24F582350366ED55475F34FFB197B0B394EA179480354C5")
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("One More Dawn supports the verified 0.8.070 game assembly. Hooks are inactive for " + Application.version + " (" + text + ")."));
				}
				else
				{
					Native.Bind();
					BossChests.Bind();
					Settings.Bind(((BaseUnityPlugin)this).Config);
					Log = ((BaseUnityPlugin)this).Logger;
					patches = new Harmony("gkj.onemoredawn");
					patches.PatchAll(typeof(Plugin).Assembly);
					Calendar.BindVisitorCalendar(patches);
					((BaseUnityPlugin)this).Logger.LogInfo((object)"One More Dawn active on 0.8.070.");
				}
			}
			catch (Exception ex)
			{
				Harmony obj = patches;
				if (obj != null)
				{
					obj.UnpatchSelf();
				}
				((BaseUnityPlugin)this).Logger.LogError((object)("One More Dawn could not bind the native game hooks. " + ex));
			}
		}

		private void OnDestroy()
		{
			Harmony obj = patches;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			Log = null;
		}
	}
	internal static class Native
	{
		private const BindingFlags PrivateInstance = BindingFlags.Instance | BindingFlags.NonPublic;

		internal static FieldInfo Remaining;

		internal static FieldInfo Overtime;

		internal static FieldInfo OraclePositions;

		internal static MethodInfo StartBoss;

		internal static MethodInfo SetWaveQuota;

		internal static void Bind()
		{
			Remaining = Field<MonsterSpawner, int>("m_MonstersToSpawn");
			Overtime = Field<DaytimeManager, bool>("m_Overtime");
			OraclePositions = Field<Oracle, Vector3[]>("positions");
			StartBoss = VoidMethod<BossSpawner>("OnDayStart", new Type[1] { typeof(int) });
			SetWaveQuota = VoidMethod<MonsterSpawner>("SetMonstersToSpawn", Array.Empty<Type>());
		}

		private static MethodInfo VoidMethod<Owner>(string name, params Type[] arguments)
		{
			MethodInfo method = typeof(Owner).GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic, null, arguments, null);
			if (method?.ReturnType != typeof(void))
			{
				throw new InvalidOperationException("Unexpected method " + typeof(Owner).Name + "." + name + ".");
			}
			return method;
		}

		private static FieldInfo Field<Owner, Value>(string name)
		{
			FieldInfo field = typeof(Owner).GetField(name, BindingFlags.Instance | BindingFlags.NonPublic);
			if (field?.FieldType != typeof(Value))
			{
				throw new InvalidOperationException("Unexpected field " + typeof(Owner).Name + "." + name + ".");
			}
			return field;
		}
	}
	[HarmonyPatch]
	internal static class Presentation
	{
		[HarmonyPatch(typeof(UIDaytimeClock), "OnSunsetStart", new Type[] { typeof(int) })]
		[HarmonyPostfix]
		private static void RestoreClock(int __0, Image[] ___jewels, Transform ___hand, Image ___castle)
		{
			if (__0 == 29 && ExtendedDay.Stopped)
			{
				((Component)((Component)___jewels[0]).transform.parent).gameObject.SetActive(true);
				((Component)___hand).gameObject.SetActive(true);
				((Component)___castle).gameObject.SetActive(true);
			}
		}

		[HarmonyPatch(typeof(UIDaytimeClockDayX), "OnDayStart", new Type[] { typeof(int) })]
		[HarmonyPrefix]
		private static bool KeepFinaleTimerOnDay29(int __0, ref float ___m_Counter, TextMeshProUGUI ___counter)
		{
			if (!ExtendedDay.Later(__0))
			{
				return true;
			}
			StopFinaleTimer(ref ___m_Counter, ___counter);
			return false;
		}

		[HarmonyPatch(typeof(UIDaytimeClockDayX), "Update", new Type[] { })]
		[HarmonyPrefix]
		private static bool StopFinaleTimerAfterBoss(ref float ___m_Counter, TextMeshProUGUI ___counter)
		{
			if (!ExtendedDay.Stopped)
			{
				return true;
			}
			StopFinaleTimer(ref ___m_Counter, ___counter);
			return false;
		}

		private static void StopFinaleTimer(ref float remaining, TextMeshProUGUI counter)
		{
			remaining = -1f;
			if (((Component)counter).gameObject.activeSelf)
			{
				((Component)counter).gameObject.SetActive(false);
			}
		}

		[HarmonyPatch(typeof(UIDeathCaption), "OnGameOver", new Type[] { })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> ShowHeroDefeat(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			MethodInfo day = AccessTools.Method(typeof(DaytimeManager), "CurrentDay", (Type[])null, (Type[])null);
			CodeInstruction obj = list[NativeIL.SingleSite(list, (CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, day)) + 1];
			if (!CodeInstructionExtensions.LoadsConstant(obj, 29L))
			{
				throw new InvalidOperationException("Expected the native Day 29 death caption check.");
			}
			obj.opcode = OpCodes.Call;
			obj.operand = AccessTools.Method(typeof(Presentation), "UseFinaleCaptionOn", (Type[])null, (Type[])null);
			return list;
		}

		private static int UseFinaleCaptionOn()
		{
			if (!ExtendedDay.Stopped)
			{
				return 29;
			}
			return -1;
		}

		[HarmonyPatch(typeof(Oracle), "OnLoad", new Type[] { typeof(int) })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> ClampOraclePosition(IEnumerable<CodeInstruction> code)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			MethodInfo week = AccessTools.Method(typeof(DaytimeManager), "CurrentWeek", (Type[])null, (Type[])null);
			return NativeIL.InsertAfter(code, (CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, week), new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Presentation), "OraclePosition", (Type[])null, (Type[])null)));
		}

		private static int OraclePosition(int week, Oracle oracle)
		{
			if (!ExtendedDay.Later(ExtendedDay.Today))
			{
				return week;
			}
			return Math.Min(week, ((Vector3[])Native.OraclePositions.GetValue(oracle)).Length - 1);
		}

		[HarmonyPatch(typeof(Oracle), "OnSetData", new Type[]
		{
			typeof(List<int>),
			typeof(bool)
		})]
		[HarmonyPostfix]
		private static void RefreshOracleForWeek(bool __1, ref bool ___m_ThisWeek)
		{
			int today = ExtendedDay.Today;
			if (__1 && ExtendedDay.Later(today) && (today - 1) % 7 == 0)
			{
				___m_ThisWeek = false;
			}
		}
	}
	internal static class Progression
	{
		internal const int Finale = 29;

		internal const int LastOrdinaryWave = 23;

		internal const int DefaultWaveGrowth = 8;

		internal const int DefaultWaveGrowthIncrease = 1;

		internal const int DefaultWaveGrowthIncreaseInterval = 1;

		internal const int MaxBaseWave = 1000000;

		internal static int WeeklyBosses(int day, int maximum = 0)
		{
			if (day <= 29 || day % 7 != 0)
			{
				return 0;
			}
			int num = 1 + (day - 1) / 28;
			if (maximum <= 0)
			{
				return num;
			}
			return Math.Min(num, maximum);
		}

		internal static int ExtendedWaveBase(int day, int nativeMinimum, int growth, int growthIncrease = 1, int interval = 1)
		{
			long num = (long)day - 29L - (day / 7 - 4);
			long num2 = num / interval;
			long num3 = num % interval;
			long val = interval * num2 * (num2 - 1) / 2 + num2 * num3;
			long num4 = num * growth + Math.Min(1000000L, val) * growthIncrease;
			return (int)Math.Min(1000000L, nativeMinimum + num4);
		}

		internal static int WaveMinimum(int day, int nativeMinimum, int growth = 8, int growthIncrease = 1, int interval = 1)
		{
			if (day > 29)
			{
				if (WeeklyBosses(day) <= 0)
				{
					return ExtendedWaveBase(day, nativeMinimum, growth, growthIncrease, interval);
				}
				return 0;
			}
			return nativeMinimum;
		}

		internal static int ReinforcementQuota(int quota, int percent)
		{
			return (int)(((long)Math.Max(0, quota) * (long)percent + 99) / 100);
		}

		internal static int AdjustBossLevel(int nativeLevel, int adjustment)
		{
			if (adjustment != 0)
			{
				return (int)Math.Clamp((long)nativeLevel + (long)adjustment, 1L, 2147483647L);
			}
			return nativeLevel;
		}

		internal static int BossTier(int weekIndex, int slot)
		{
			return ((weekIndex - 4) % 4 + slot % 4) % 4;
		}
	}
	internal sealed class BossSequence<T> where T : class
	{
		private readonly int total;

		private readonly ConditionalWeakTable<T, object> finishedBosses = new ConditionalWeakTable<T, object>();

		private T active;

		private bool starting;

		internal int Finished { get; private set; }

		internal bool Defeated { get; private set; }

		internal int Total => total;

		internal bool ReinforcementsStarted { get; private set; }

		internal bool Complete => Finished == total;

		internal bool Ready
		{
			get
			{
				if (!Complete && !starting)
				{
					return active == null;
				}
				return false;
			}
		}

		internal BossSequence(int total)
		{
			this.total = total;
		}

		internal bool TryBegin()
		{
			if (!Ready)
			{
				return false;
			}
			starting = true;
			return true;
		}

		internal void Spawned(T boss)
		{
			if (!starting || boss == null)
			{
				throw new InvalidOperationException("A boss arrived outside its reserved slot.");
			}
			active = boss;
			starting = false;
			ReinforcementsStarted = false;
		}

		internal bool Owns(T boss)
		{
			if (active != null)
			{
				return active == boss;
			}
			return false;
		}

		internal bool WasFinished(T boss)
		{
			object value;
			if (boss != null)
			{
				return finishedBosses.TryGetValue(boss, out value);
			}
			return false;
		}

		internal bool TryStartReinforcements(T boss)
		{
			if (ReinforcementsStarted || Defeated || !Owns(boss))
			{
				return false;
			}
			ReinforcementsStarted = true;
			return true;
		}

		internal bool TryDefeat(T boss)
		{
			if (Defeated || !Owns(boss))
			{
				return false;
			}
			Defeated = true;
			return true;
		}

		internal bool FinishRewards(T boss)
		{
			if (!Defeated || !Owns(boss))
			{
				return false;
			}
			finishedBosses.GetOrCreateValue(boss);
			Finished++;
			active = null;
			Defeated = false;
			return true;
		}
	}
	internal static class Settings
	{
		private const int DefaultReinforcementWavePercent = 50;

		internal static int WaveGrowth { get; private set; } = 8;

		internal static int WaveGrowthIncrease { get; private set; } = 1;

		internal static int WaveGrowthIncreaseInterval { get; private set; } = 1;

		internal static int BossLevelOffset { get; private set; }

		internal static int BossCountCap { get; private set; }

		internal static int ReinforcementsPercent { get; private set; } = 50;

		internal static void Bind(ConfigFile config)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Expected O, but got Unknown
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Expected O, but got Unknown
			WaveGrowth = config.Bind<int>("Waves", "WaveGrowthPerDay", 8, new ConfigDescription("Extra enemies added to the base quota on Day 30, before Curse and Bonfires. This is the starting increase for later ordinary waves.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000000), Array.Empty<object>())).Value;
			WaveGrowthIncrease = config.Bind<int>("Waves", "WaveGrowthIncreasePerDay", 1, new ConfigDescription("How much to raise the wave growth at each interval. Set to 0 for a constant increase.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000000), Array.Empty<object>())).Value;
			WaveGrowthIncreaseInterval = config.Bind<int>("Waves", "WaveGrowthIncreaseInterval", 1, new ConfigDescription("Ordinary nights between increases to wave growth. An interval of 2 applies each growth amount to two ordinary waves. Boss nights are skipped.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, int.MaxValue), Array.Empty<object>())).Value;
			BossLevelOffset = config.Bind<int>("Bosses", "BossLevelAdjustment", 0, new ConfigDescription("Levels added to each post-Day-29 weekly boss. Negative values make bosses weaker. The minimum level is 1.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-1000, 1000), Array.Empty<object>())).Value;
			BossCountCap = config.Bind<int>("Bosses", "MaximumBossesPerNight", 0, new ConfigDescription("Maximum bosses on each post-Day-29 boss night. Set to 0 for the original uncapped schedule.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, int.MaxValue), Array.Empty<object>())).Value;
			bool value = config.Bind<bool>("Bosses", "EnableBossReinforcements", true, "Give each boss after Day 29 its own wave of enemies, starting after the boss intro.").Value;
			int value2 = config.Bind<int>("Bosses", "BossReinforcementWavePercent", 50, new ConfigDescription("Percentage of a normal wave, after Curse and Bonfires, spawned for each boss when reinforcements are enabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())).Value;
			ReinforcementsPercent = (value ? value2 : 0);
		}

		internal static int BossCount(int day)
		{
			return Progression.WeeklyBosses(day, BossCountCap);
		}
	}
	[HarmonyPatch]
	internal static class Settlement
	{
		[HarmonyPatch(typeof(DaytimeManager), "GetDayLimit", new Type[] { })]
		[HarmonyPostfix]
		private static void AllowCheckpointDay(DaytimeManager __instance, ref int __result)
		{
			if (!ExtendedDay.Later(__instance.CurrentDay()))
			{
				ExtendedDay extendedDay = ExtendedDay.Find(__instance);
				if (extendedDay == null || extendedDay.Bosses?.Complete != true)
				{
					return;
				}
			}
			__result = int.MaxValue;
		}

		[HarmonyPatch(typeof(DaytimeManager), "Update", new Type[] { })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> DelayCombatEnd(IEnumerable<CodeInstruction> code)
		{
			return GuardMonsters(code, "BeforeCombatEnd");
		}

		[HarmonyPatch(typeof(DaytimeManager), "SwitchState", new Type[] { })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> ReleaseFinaleAndWaitForClearance(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = GuardMonsters(instructions, "BeforeNight");
			MethodInfo currentDay = AccessTools.Method(typeof(DaytimeManager), "CurrentDay", (Type[])null, (Type[])null);
			int num = NativeIL.SingleSite(list, (CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, currentDay));
			CodeInstruction obj = list[num + 1];
			if (!CodeInstructionExtensions.LoadsConstant(obj, 29L))
			{
				throw new InvalidOperationException("Expected the native Day 29 overtime comparison.");
			}
			obj.opcode = OpCodes.Call;
			obj.operand = AccessTools.Method(typeof(Settlement), "DayThatHoldsTheClock", (Type[])null, (Type[])null);
			return list;
		}

		private static List<CodeInstruction> GuardMonsters(IEnumerable<CodeInstruction> code, string callback)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			MethodInfo count = AccessTools.Method(typeof(CombatManager), "CurrentMonstersAmount", (Type[])null, (Type[])null);
			return NativeIL.InsertAfter(code, (CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, count), new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Settlement), callback, (Type[])null, (Type[])null)));
		}

		private static int DayThatHoldsTheClock()
		{
			if (!ExtendedDay.Stopped || !ExtendedDay.Current.Bosses.Complete)
			{
				return 29;
			}
			return -1;
		}

		private static int BeforeCombatEnd(int actual)
		{
			if (actual != 0 || !ExtendedDay.Pending(DaytimeManager.Instance))
			{
				return actual;
			}
			return 1;
		}

		private static int BeforeNight(int actual)
		{
			if (actual != 0 || !ExtendedDay.Managed || (!ExtendedDay.Pending(DaytimeManager.Instance) && CombatManager.Instance.IsCombatOver()))
			{
				return actual;
			}
			return 1;
		}

		[HarmonyPatch(typeof(CombatManager), "CombatEnd", new Type[] { })]
		[HarmonyPrefix]
		private static bool ClaimCombatEnd()
		{
			if (!ExtendedDay.Managed || GameManager.Instance.IsGameOver())
			{
				return true;
			}
			ExtendedDay extendedDay = ExtendedDay.Get(DaytimeManager.Instance);
			if (extendedDay.CombatEnded || ExtendedDay.Pending(DaytimeManager.Instance))
			{
				return false;
			}
			extendedDay.CombatEnded = true;
			return true;
		}

		[HarmonyPatch(typeof(GameManager), "EndDay", new Type[] { typeof(bool) })]
		[HarmonyPrefix]
		private static bool AllowTavernRequest()
		{
			if (ExtendedDay.Managed)
			{
				ExtendedDay current = ExtendedDay.Current;
				if (current == null || !current.SettlementStarted)
				{
					return ExtendedDay.CanSettle();
				}
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(GameManager), "ChangeState", new Type[] { typeof(GameState) })]
		[HarmonyPrefix]
		private static bool ClaimSettlement(GameState __0)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			if ((int)__0 == 6 && (ExtendedDay.Stopped || ExtendedDay.Later(ExtendedDay.Today)))
			{
				return false;
			}
			if ((int)__0 != 4 || !ExtendedDay.Managed)
			{
				return true;
			}
			ExtendedDay extendedDay = ExtendedDay.Get(DaytimeManager.Instance);
			if (extendedDay.SettlementStarted || !ExtendedDay.CanSettle())
			{
				return false;
			}
			extendedDay.SettlementStarted = true;
			return true;
		}

		[HarmonyPatch(typeof(GameManager), "TriggerEnd", new Type[] { })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> PreserveDefeat(IEnumerable<CodeInstruction> code)
		{
			return NativeIL.ReplaceCall(code, AccessTools.Method(typeof(BossSpawner), "IsBossDead", (Type[])null, (Type[])null), AccessTools.Method(typeof(Settlement), "CountsAsFinaleWin", (Type[])null, (Type[])null));
		}

		[HarmonyPatch(typeof(GameManager), "SaveAndUnload", new Type[] { })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> PreserveDefeatOnSave(IEnumerable<CodeInstruction> code)
		{
			return PreserveDefeat(code);
		}

		private static bool CountsAsFinaleWin(BossSpawner spawner)
		{
			if (!ExtendedDay.Stopped)
			{
				return spawner.IsBossDead();
			}
			return false;
		}

		[HarmonyPatch(typeof(GameManager), "MaybeOpenCongratsOverlay", new Type[] { })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> GiveUpSummary(IEnumerable<CodeInstruction> instructions)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			MethodInfo overlay = AccessTools.Method(typeof(OverlayManager), "OpenGameOver", new Type[1] { typeof(bool) }, (Type[])null);
			int index = NativeIL.SingleSite(list, (CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, overlay));
			list.Insert(index, new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Settlement), "ShowDefeat", (Type[])null, (Type[])null)));
			return list;
		}

		private static bool ShowDefeat(bool nativeValue)
		{
			if (!nativeValue)
			{
				return ExtendedDay.Stopped;
			}
			return true;
		}
	}
	[HarmonyPatch]
	internal static class Waves
	{
		[HarmonyPatch(typeof(MonsterSpawner), "SetMonstersToSpawn", new Type[] { })]
		[HarmonyPrefix]
		private static void PinRoster(MonsterSpawner __instance, ref int ___m_CurrentWave, ref int ___m_Difficulty)
		{
			if (ExtendedDay.Later(ExtendedDay.Today))
			{
				___m_CurrentWave = RosterCeiling(__instance);
				___m_Difficulty = ___m_CurrentWave + 1;
			}
		}

		[HarmonyPatch(typeof(MonsterSpawner), "SetMonstersToSpawn", new Type[] { })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> ExtendBaseQuota(IEnumerable<CodeInstruction> code)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			FieldInfo minimum = AccessTools.Field(typeof(Wave), "minimum");
			return NativeIL.InsertAfter(code, (CodeInstruction instruction) => CodeInstructionExtensions.LoadsField(instruction, minimum, false), new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Waves), "BaseQuota", (Type[])null, (Type[])null)));
		}

		private static int BaseQuota(int minimum)
		{
			int today = ExtendedDay.Today;
			if (!ExtendedDay.Later(today))
			{
				return minimum;
			}
			int waveGrowth = Settings.WaveGrowth;
			int waveGrowthIncrease = Settings.WaveGrowthIncrease;
			int waveGrowthIncreaseInterval = Settings.WaveGrowthIncreaseInterval;
			ExtendedDay current = ExtendedDay.Current;
			if (current == null || !current.PreparingBossWave)
			{
				return Progression.WaveMinimum(today, minimum, waveGrowth, waveGrowthIncrease, waveGrowthIncreaseInterval);
			}
			return Progression.ExtendedWaveBase(today, minimum, waveGrowth, waveGrowthIncrease, waveGrowthIncreaseInterval);
		}

		internal static void StartBossReinforcements(ExtendedDay state)
		{
			state.PreparingBossWave = true;
			try
			{
				Native.SetWaveQuota.Invoke(MonsterSpawner.Instance, null);
			}
			finally
			{
				state.PreparingBossWave = false;
			}
		}

		[HarmonyPatch(typeof(MonsterSpawner), "SetMonstersToSpawn", new Type[] { })]
		[HarmonyPostfix]
		private static void SetReinforcementQuota(ref int ___m_MaxMonstersToSpawn, ref int ___m_MinMonstersToSpawn, ref int ___m_MonstersToSpawn, ref float ___m_SpawnCountdown, ref float ___m_SpawnTimer)
		{
			ExtendedDay current = ExtendedDay.Current;
			if (current != null && current.PreparingBossWave)
			{
				int reinforcementsPercent = Settings.ReinforcementsPercent;
				___m_MaxMonstersToSpawn = Progression.ReinforcementQuota(___m_MaxMonstersToSpawn, reinforcementsPercent);
				___m_MinMonstersToSpawn = Progression.ReinforcementQuota(___m_MinMonstersToSpawn, reinforcementsPercent);
				___m_MonstersToSpawn = ___m_MinMonstersToSpawn;
				___m_SpawnCountdown *= (float)reinforcementsPercent / 100f;
				___m_SpawnTimer = 0f;
			}
		}

		internal static bool HasBossReinforcements(BossSequence<Boss> sequence)
		{
			MonsterSpawner instance = MonsterSpawner.Instance;
			if (sequence != null && sequence.ReinforcementsStarted && (Object)(object)instance != (Object)null)
			{
				return instance.GetMonstersToSpawn() > 0;
			}
			return false;
		}

		[HarmonyPatch(typeof(MonsterSpawner), "FixedUpdate", new Type[] { })]
		[HarmonyPrefix]
		private static bool StopOrdinarySpawner(MonsterSpawner __instance)
		{
			int today = ExtendedDay.Today;
			if (ExtendedDay.Stopped)
			{
				return false;
			}
			if (ExtendedDay.Later(today))
			{
				if (!GameManager.Instance.IsGameOver())
				{
					return __instance.GetMonstersToSpawn() > 0;
				}
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(MonsterSpawner), "FixedUpdate", new Type[] { })]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> ClampRandomTier(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			int num = NativeIL.SingleSite(list, (CodeInstruction instruction) => instruction.opcode == OpCodes.Ldelem_Ref);
			CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
			CodeInstructionExtensions.MoveLabelsFrom(val, list[num]);
			list.Insert(num, val);
			list.Insert(num + 1, new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Waves), "SafeTier", (Type[])null, (Type[])null)));
			return list;
		}

		private static int SafeTier(int index, MonsterSpawner spawner)
		{
			if (!ExtendedDay.Later(ExtendedDay.Today))
			{
				return index;
			}
			return Math.Min(index, RosterCeiling(spawner));
		}

		[HarmonyPatch(typeof(DaytimeManager), "CanMonstersSpawn", new Type[] { })]
		[HarmonyPostfix]
		private static void FinishQuotaAfterSunset(DaytimeManager __instance, ref bool __result)
		{
			int day = __instance.CurrentDay();
			ExtendedDay extendedDay = ExtendedDay.Find(__instance);
			if (extendedDay != null && extendedDay.HordeStopped)
			{
				__result = false;
				return;
			}
			MonsterSpawner instance = MonsterSpawner.Instance;
			if (ExtendedDay.Weekly(day))
			{
				if (HasBossReinforcements(ExtendedDay.Current?.Bosses))
				{
					BossSpawner instance2 = BossSpawner.Instance;
					__result = (__instance.IsSpawnTime() || __instance.IsEvening()) && !GameManager.Instance.IsGameOver() && (Object)(object)instance2 != (Object)null && !instance2.IsInAnimation() && !instance2.IsBossDying();
				}
			}
			else if (!__result && ExtendedDay.Later(day) && __instance.IsEvening() && (Object)(object)instance != (Object)null && instance.GetMonstersToSpawn() > 0 && !GameManager.Instance.IsGameOver())
			{
				__result = true;
			}
		}

		private static int RosterCeiling(MonsterSpawner spawner)
		{
			return Math.Min(23, spawner.waves.Length - 1);
		}

		[HarmonyPatch(typeof(VillainSpawner), "Update", new Type[] { })]
		[HarmonyPrefix]
		private static bool StopFinaleVillains(ref float ___m_WaitTimer)
		{
			if (!ExtendedDay.Stopped)
			{
				return true;
			}
			if (___m_WaitTimer > 0f)
			{
				___m_WaitTimer = -1f;
			}
			return false;
		}
	}
}