Decompiled source of HoldTheLine v0.2.3

plugins/HoldTheLine.dll

Decompiled 14 minutes ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
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 System.Text;
using BepInEx;
using HarmonyLib;
using Newtonsoft.Json;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Tavern;
using SuperFantasyKingdom.UI;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.UI;
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("HoldTheLine")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.3.0")]
[assembly: AssemblyInformationalVersion("0.2.3+101869a84167cf4f4ed523dcdd929eaca4c66eba")]
[assembly: AssemblyProduct("HoldTheLine")]
[assembly: AssemblyTitle("HoldTheLine")]
[assembly: AssemblyVersion("0.2.3.0")]
namespace HoldTheLine;

internal static class Checkpoint
{
	internal sealed class Header
	{
		public string runID { get; set; }

		public string hash { get; set; }

		public Wager gkjHoldTheLine { get; set; }
	}

	internal static Header Read(string json)
	{
		if (string.IsNullOrEmpty(json))
		{
			return null;
		}
		try
		{
			return JsonConvert.DeserializeObject<Header>(json);
		}
		catch (JsonException)
		{
			return null;
		}
	}

	internal static Wager Restore(Header record, string run, string hash)
	{
		Wager wager = record?.gkjHoldTheLine;
		if (wager == null || string.IsNullOrEmpty(run) || !(record.runID == run) || !(record.hash == hash) || !(wager.Run == run) || wager.Day <= 0 || !Enum.IsDefined(typeof(Decision), wager.State) || !Enum.IsDefined(typeof(WagerKind), wager.Kind) || wager.Unclaimed == null || !wager.Unclaimed.TrueForAll((RelicPrize p) => p != null && p.Night > 0 && RelicPrize.Valid(p.Choices)) || (wager.Kind == WagerKind.Relic && !RelicPrize.Valid(wager.Choices)))
		{
			return null;
		}
		return wager;
	}

	internal static string Attach(string json, Wager wager)
	{
		if (wager == null)
		{
			return json;
		}
		Header header = Read(json);
		if (header == null || header.runID != wager.Run || header.gkjHoldTheLine != null)
		{
			return json;
		}
		int startIndex = json.LastIndexOf('}');
		return json.Insert(startIndex, ",\"gkjHoldTheLine\":" + JsonConvert.SerializeObject((object)wager));
	}
}
internal sealed class OfferCard
{
	private static readonly Lazy<Sprite> Treasury = new Lazy<Sprite>((Func<Sprite>)(() => LoadArt("Coin")));

	private static readonly Lazy<Sprite> Reliquary = new Lazy<Sprite>((Func<Sprite>)(() => LoadArt("Relic")));

	private static readonly Lazy<Sprite> BronzeFrame = new Lazy<Sprite>((Func<Sprite>)(() => LoadArt("CoinFrame")));

	private static readonly Lazy<Sprite> SilverFrame = new Lazy<Sprite>((Func<Sprite>)(() => LoadArt("RelicFrame")));

	private const float CardWidth = 280f;

	private const float CardHeight = 420f;

	private const float Gap = 16f;

	private readonly UIOverlayMessage view;

	private readonly Vector2 center;

	private Vector2 viewport;

	private readonly Button accept;

	private readonly Button pass;

	private readonly Button relic;

	private readonly Button lower;

	private readonly Button higher;

	private readonly TextMeshProUGUI priceText;

	private readonly TextMeshProUGUI relicText;

	private readonly Text stakeCount;

	private bool hasThree;

	private int profit = 1;

	private int lastCoins = -1;

	private readonly int opened;

	private readonly int night;

	private bool release;

	private readonly TextMeshProUGUI body;

	internal bool Exists => (Object)(object)view != (Object)null;

	private static InputSystemUIInputModule Input
	{
		get
		{
			EventSystem current = EventSystem.current;
			BaseInputModule obj = ((current != null) ? current.currentInputModule : null);
			return (InputSystemUIInputModule)(object)((obj is InputSystemUIInputModule) ? obj : null);
		}
	}

	internal OfferCard(int day, bool relicAvailable, Action<int> stake, Action stakeRelic, Action decline)
	{
		//IL_005b: 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)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_0193: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: Expected O, but got Unknown
		//IL_029c: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a2: Expected O, but got Unknown
		//IL_0312: Unknown result type (might be due to invalid IL or missing references)
		//IL_0359: Unknown result type (might be due to invalid IL or missing references)
		OfferCard offerCard = this;
		night = day;
		hasThree = relicAvailable;
		view = OverlayManager.Instance.OverlayMessage(true);
		center = ((RectTransform)((Component)view).transform).anchoredPosition;
		FitDialog();
		opened = Time.frameCount;
		InputSystemUIInputModule input = Input;
		int num;
		if (input == null)
		{
			num = 0;
		}
		else
		{
			InputActionReference submit = input.submit;
			num = ((((submit != null) ? new bool?(submit.action.IsPressed()) : ((bool?)null)) == true) ? 1 : 0);
		}
		release = (byte)num != 0;
		body = ((Component)((Component)view).transform.Find("Message")).GetComponent<TextMeshProUGUI>();
		((Component)body).GetComponent<LayoutElement>().preferredWidth = 576f;
		((TMP_Text)body).rectTransform.SetSizeWithCurrentAnchors((Axis)0, 576f);
		((TMP_Text)body).enableWordWrapping = true;
		VerticalLayoutGroup component = ((Component)view).GetComponent<VerticalLayoutGroup>();
		((LayoutGroup)component).childAlignment = (TextAnchor)1;
		((HorizontalOrVerticalLayoutGroup)component).spacing = 7f;
		Heading(576f);
		view.SetMessage($"Keep the Castle Wall unharmed through Night {night}.\nAny damage costs your stake, even if repaired.");
		view.RemoveAccept();
		pass = ((Component)((Component)view).transform.Find("Buttons/Cancel")).GetComponent<Button>();
		view.SetCancel("Pass", (UnityAction)delegate
		{
			offerCard.Invoke(decline);
		});
		HorizontalLayoutGroup obj = ((Component)((Component)pass).transform.parent).gameObject.AddComponent<HorizontalLayoutGroup>();
		((LayoutGroup)obj).childAlignment = (TextAnchor)4;
		((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = (((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = false);
		((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = (((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = false);
		GameObject row = Row("Wager cards", 16f);
		accept = Choice(row, "Coin Wager", Treasury.Value, BronzeFrame.Value, delegate
		{
			stake(offerCard.profit);
		});
		relic = Choice(row, "Relic Wager", Reliquary.Value, SilverFrame.Value, stakeRelic);
		Label(((Component)accept).transform, "Stake in coins", 282f, 27f, 25f);
		RectTransform val = (RectTransform)Object.Instantiate<Transform>(Resources.Load<GameObject>("UI/OverlayElementWorker").transform.Find("Amount"), ((Component)accept).transform, false);
		((Object)val).name = "Stake";
		Place(val, 0f, 314f, 94f, 32f);
		lower = Arrow(val, "Less", -1);
		higher = Arrow(val, "More", 1);
		Image obj2 = ((Component)val).GetComponent<Image>() ?? ((Component)val).gameObject.AddComponent<Image>();
		((Graphic)obj2).color = new Color(0.09f, 0.08f, 0.08f);
		((Graphic)obj2).raycastTarget = true;
		((Component)val).gameObject.AddComponent<StakeCounter>();
		stakeCount = ((Component)((Transform)val).Find("Text")).GetComponent<Text>();
		((Graphic)stakeCount).color = new Color(1f, 0.96f, 0.84f);
		((Graphic)stakeCount).raycastTarget = false;
		stakeCount.resizeTextForBestFit = true;
		stakeCount.resizeTextMinSize = 11;
		stakeCount.resizeTextMaxSize = 24;
		priceText = Label(((Component)accept).transform, "", 369f, 60f, 26f);
		Label(((Component)relic).transform, "Stake 20 coins", 308f, 46f, 29f);
		relicText = Label(((Component)relic).transform, "", 369f, 60f, 26f);
		UpdateTerms(ResourceManager.Instance.GetCoins());
		GamepadManager.Instance.SetGameObjectToSelect(((Component)pass).gameObject, true);
		EventSystem current = EventSystem.current;
		if (current != null)
		{
			current.SetSelectedGameObject(((Component)pass).gameObject);
		}
	}

	private void FitDialog()
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		float uIScaling = SettingsManager.Instance.GetUIScaling();
		Vector2 val = new Vector2((float)Screen.width, (float)Screen.height) / uIScaling;
		if (!(val == viewport))
		{
			viewport = val;
			float num = Mathf.Min(new float[3]
			{
				1f,
				val.x / 656f,
				val.y / 756f
			});
			RectTransform val2 = (RectTransform)((Component)view).transform;
			((Transform)val2).localScale = Vector3.one * num;
			val2.anchoredPosition = center + Vector2.down * (40f * num);
		}
	}

	private void Heading(float width)
	{
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		Transform val = ((Component)OverlayManager.Instance).transform.Find("Overlay/SizeSelection/HeaderContainer/Header");
		if (!((Object)(object)val == (Object)null))
		{
			Transform val2 = Object.Instantiate<Transform>(val, ((Component)view).transform, false);
			((Object)val2).name = "Wager heading";
			val2.SetAsFirstSibling();
			((Component)val2).gameObject.SetActive(true);
			LayoutElement obj = ((Component)val2).GetComponent<LayoutElement>() ?? ((Component)val2).gameObject.AddComponent<LayoutElement>();
			obj.ignoreLayout = false;
			obj.preferredWidth = width;
			float minHeight = (obj.preferredHeight = 46f);
			obj.minHeight = minHeight;
			TextMeshProUGUI component = ((Component)val2.Find("Text")).GetComponent<TextMeshProUGUI>();
			LocalizeStringEvent component2 = ((Component)component).GetComponent<LocalizeStringEvent>();
			if ((Object)(object)component2 != (Object)null)
			{
				((Behaviour)component2).enabled = false;
			}
			((TMP_Text)component).text = "Hold the Line";
			RectTransform rectTransform = ((TMP_Text)component).rectTransform;
			rectTransform.anchoredPosition += Vector2.down * 4f;
			Graphic[] componentsInChildren = ((Component)val2).GetComponentsInChildren<Graphic>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].raycastTarget = false;
			}
		}
	}

	private GameObject Row(string name, float spacing)
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Expected O, but got Unknown
		GameObject val = new GameObject(name, new Type[2]
		{
			typeof(RectTransform),
			typeof(HorizontalLayoutGroup)
		});
		val.transform.SetParent(((Component)view).transform, false);
		val.transform.SetSiblingIndex(((Component)view).transform.Find("Buttons").GetSiblingIndex());
		HorizontalLayoutGroup component = val.GetComponent<HorizontalLayoutGroup>();
		((LayoutGroup)component).childAlignment = (TextAnchor)4;
		bool childForceExpandWidth = (((HorizontalOrVerticalLayoutGroup)component).childForceExpandHeight = false);
		((HorizontalOrVerticalLayoutGroup)component).childForceExpandWidth = childForceExpandWidth;
		((HorizontalOrVerticalLayoutGroup)component).spacing = spacing;
		return val;
	}

	private static void Place(RectTransform rect, float x, float y, float width, float height)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		Vector2 val = default(Vector2);
		((Vector2)(ref val))..ctor(0.5f, 1f);
		rect.anchorMax = val;
		rect.anchorMin = val;
		rect.pivot = new Vector2(0.5f, 0.5f);
		rect.sizeDelta = new Vector2(width, height);
		rect.anchoredPosition = new Vector2(x, 0f - y);
	}

	private Button Choice(GameObject row, string title, Sprite artwork, Sprite frameArt, Action action)
	{
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Expected O, but got Unknown
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: 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_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_014a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Expected O, but got Unknown
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject(title, new Type[4]
		{
			typeof(RectTransform),
			typeof(Image),
			typeof(LayoutElement),
			typeof(Button)
		});
		val.transform.SetParent(row.transform, false);
		LayoutElement component = val.GetComponent<LayoutElement>();
		component.preferredWidth = 280f;
		component.preferredHeight = 420f;
		Image component2 = val.GetComponent<Image>();
		component2.sprite = frameArt;
		Button component3 = val.GetComponent<Button>();
		((Selectable)component3).targetGraphic = (Graphic)(object)component2;
		ColorBlock colors = ((Selectable)component3).colors;
		((ColorBlock)(ref colors)).normalColor = new Color(0.94f, 0.94f, 0.94f);
		Color selectedColor = (((ColorBlock)(ref colors)).highlightedColor = Color.white);
		((ColorBlock)(ref colors)).selectedColor = selectedColor;
		((ColorBlock)(ref colors)).disabledColor = new Color(0.67f, 0.67f, 0.67f);
		((Selectable)component3).colors = colors;
		Outline val2 = val.AddComponent<Outline>();
		((Shadow)val2).effectColor = Color.white;
		((Shadow)val2).effectDistance = new Vector2(3f, -3f);
		((Behaviour)val2).enabled = false;
		val.AddComponent<WagerCardFocus>().Frame = val2;
		((UnityEvent)component3.onClick).AddListener((UnityAction)delegate
		{
			Invoke(action);
		});
		Image component4 = new GameObject("Illustration", new Type[2]
		{
			typeof(RectTransform),
			typeof(Image)
		}).GetComponent<Image>();
		((Component)component4).transform.SetParent(val.transform, false);
		component4.sprite = artwork;
		((Graphic)component4).raycastTarget = false;
		Place(((Graphic)component4).rectTransform, 0f, 114f, 264f, 212f);
		((TMP_Text)Label(val.transform, title, 243f, 42f, 34f)).fontStyle = (FontStyles)1;
		return component3;
	}

	private static Sprite LoadArt(string name)
	{
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Expected O, but got Unknown
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		using Stream stream = typeof(OfferCard).Assembly.GetManifestResourceStream("HoldTheLine.Art." + name);
		using MemoryStream memoryStream = new MemoryStream();
		stream.CopyTo(memoryStream);
		Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
		ImageConversion.LoadImage(val, memoryStream.ToArray(), true);
		((Texture)val).filterMode = (FilterMode)0;
		((Texture)val).wrapMode = (TextureWrapMode)1;
		((Object)val).hideFlags = (HideFlags)61;
		Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
		((Object)obj).hideFlags = (HideFlags)61;
		return obj;
	}

	private TextMeshProUGUI Label(Transform parent, string value, float y, float height, float size)
	{
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		TextMeshProUGUI component = new GameObject("Text", new Type[2]
		{
			typeof(RectTransform),
			typeof(TextMeshProUGUI)
		}).GetComponent<TextMeshProUGUI>();
		((TMP_Text)component).transform.SetParent(parent, false);
		((TMP_Text)component).font = ((TMP_Text)body).font;
		((TMP_Text)component).fontSharedMaterial = ((TMP_Text)body).fontSharedMaterial;
		((TMP_Text)component).fontSize = size;
		((Graphic)component).color = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)245, (byte)220, byte.MaxValue));
		((Graphic)component).raycastTarget = false;
		((TMP_Text)component).text = value;
		((TMP_Text)component).alignment = (TextAlignmentOptions)514;
		Place(((TMP_Text)component).rectTransform, 0f, y, 0f, height);
		((TMP_Text)component).rectTransform.anchorMin = new Vector2(0f, 1f);
		((TMP_Text)component).rectTransform.anchorMax = Vector2.one;
		((TMP_Text)component).rectTransform.sizeDelta = new Vector2(-12f, height);
		return component;
	}

	private Button Arrow(RectTransform amount, string name, int step)
	{
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Expected O, but got Unknown
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Expected O, but got Unknown
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Expected O, but got Unknown
		Button component = ((Component)((Transform)amount).Find(name)).GetComponent<Button>();
		Place((RectTransform)((Component)component).transform, (float)step * 66f, 16f, 26f, 32f);
		component.onClick = new ButtonClickedEvent();
		((UnityEvent)component.onClick).AddListener((UnityAction)delegate
		{
			Invoke(delegate
			{
				Adjust(step);
			});
		});
		return component;
	}

	internal void RefreshRelicOffer(bool available)
	{
		hasThree = available;
		UpdateTerms(ResourceManager.Instance.GetCoins());
	}

	private void Adjust(int delta)
	{
		int num = profit + delta;
		if (!CoinTerms.Quote(num, out var stake, out var _) || stake > lastCoins)
		{
			return;
		}
		profit = num;
		UpdateTerms(lastCoins);
		EventSystem current = EventSystem.current;
		if (current != null)
		{
			GameObject currentSelectedGameObject = current.currentSelectedGameObject;
			bool? obj;
			if (currentSelectedGameObject == null)
			{
				obj = null;
			}
			else
			{
				Button component = currentSelectedGameObject.GetComponent<Button>();
				obj = ((component != null) ? new bool?(((Selectable)component).interactable) : ((bool?)null));
			}
			if (obj == false)
			{
				Button val = ((delta > 0) ? lower : higher);
				EventSystem.current.SetSelectedGameObject(((Selectable)val).interactable ? ((Component)val).gameObject : ((Component)accept).gameObject);
			}
		}
	}

	private void UpdateTerms(int coins)
	{
		lastCoins = coins;
		int stake;
		int total;
		while (profit > 1 && CoinTerms.Quote(profit, out stake, out total) && stake > coins)
		{
			profit--;
		}
		CoinTerms.Quote(profit, out var stake2, out var total2);
		stakeCount.text = stake2.ToString();
		((TMP_Text)priceText).text = $"Total return {total2}\nNet profit +{profit}";
		((TMP_Text)relicText).text = ((!hasThree) ? "Fewer than 3 eligible relics" : ((coins < 20) ? $"Choose 1 of 3 relics\nNeed {20 - coins} more coins" : "Choose 1 of 3 relics"));
		((Selectable)accept).interactable = coins >= stake2 && (long)coins + (long)profit <= int.MaxValue;
		((Selectable)relic).interactable = hasThree && coins >= 20;
		((Selectable)lower).interactable = profit > 1;
		((Selectable)higher).interactable = CoinTerms.Quote(profit + 1, out var stake3, out total) && stake3 <= coins && (long)coins + (long)profit + 1 <= int.MaxValue;
		Button val = (((Selectable)accept).interactable ? accept : pass);
		Button val2 = (((Selectable)relic).interactable ? relic : pass);
		Button val3 = (((Selectable)higher).interactable ? higher : (((Selectable)lower).interactable ? lower : val));
		Navigate(pass, val, ((Object)(object)val2 == (Object)(object)pass) ? val : val2, val, val2);
		Navigate(accept, pass, val2, pass, ((Object)(object)val3 == (Object)(object)accept) ? pass : val3);
		Navigate(relic, val, pass, pass, pass);
		Navigate(lower, val, ((Selectable)higher).interactable ? higher : val2, val, pass);
		Navigate(higher, ((Selectable)lower).interactable ? lower : val, val2, val, pass);
	}

	private static void Navigate(Button button, Button left, Button right, Button up, Button down)
	{
		//IL_0003: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		Navigation navigation = default(Navigation);
		((Navigation)(ref navigation)).mode = (Mode)4;
		((Navigation)(ref navigation)).selectOnLeft = (Selectable)(object)left;
		((Navigation)(ref navigation)).selectOnRight = (Selectable)(object)right;
		((Navigation)(ref navigation)).selectOnUp = (Selectable)(object)up;
		((Navigation)(ref navigation)).selectOnDown = (Selectable)(object)down;
		((Selectable)button).navigation = navigation;
	}

	private void Invoke(Action action)
	{
		if ((Object)(object)view != (Object)null && ((Component)view).gameObject.activeInHierarchy && !release && Time.frameCount != opened)
		{
			action();
		}
	}

	internal void Refresh()
	{
		if ((Object)(object)view == (Object)null || !((Component)view).gameObject.activeInHierarchy)
		{
			return;
		}
		FitDialog();
		InputSystemUIInputModule input = Input;
		if (release)
		{
			if (input != null)
			{
				InputActionReference submit = input.submit;
				if (((submit != null) ? new bool?(submit.action.IsPressed()) : ((bool?)null)) == true)
				{
					goto IL_0075;
				}
			}
			release = false;
		}
		goto IL_0075;
		IL_0075:
		GamepadManager instance = GamepadManager.Instance;
		int coins = ResourceManager.Instance.GetCoins();
		if (lastCoins != coins)
		{
			UpdateTerms(coins);
		}
		EventSystem current = EventSystem.current;
		if (PauseMenuManger.Instance.InMenu() || !((Object)(object)current != (Object)null))
		{
			return;
		}
		if (!((Object)(object)current.currentSelectedGameObject == (Object)null))
		{
			Button component = current.currentSelectedGameObject.GetComponent<Button>();
			if (component == null || ((Selectable)component).interactable)
			{
				return;
			}
		}
		instance.SetGameObjectToSelect(((Component)pass).gameObject, true);
		current.SetSelectedGameObject(((Component)pass).gameObject);
	}
}
internal sealed class StakeCounter : MonoBehaviour, IPointerClickHandler, IEventSystemHandler
{
	public void OnPointerClick(PointerEventData _)
	{
	}
}
internal sealed class WagerCardFocus : MonoBehaviour, ISelectHandler, IEventSystemHandler, IDeselectHandler
{
	internal Outline Frame;

	public void OnSelect(BaseEventData _)
	{
		((Behaviour)Frame).enabled = true;
	}

	public void OnDeselect(BaseEventData _)
	{
		((Behaviour)Frame).enabled = false;
	}
}
[BepInPlugin("gkj.holdtheline", "Hold the Line", "0.2.3")]
public sealed class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(OverlayManager), "OpenGameOver")]
	private static class VictoryReward
	{
		private static bool Prefix(bool __0)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Invalid comparison between Unknown and I4
			if (__0 || (Object)(object)instance == (Object)null || instance.finishingRun || Current == null || Current.Unclaimed.Count == 0 || Current.Run != GameDataManager.Instance.GetRunID() || (int)GameManager.Instance.GetGameState() != 6)
			{
				return true;
			}
			instance.finishingRun = true;
			instance.OpenClaim(Current, Current.Unclaimed[0]);
			return false;
		}
	}

	internal static Wager Current;

	private Harmony patches;

	private OfferCard card;

	private float readySince = -1f;

	private Wager announced;

	private int claimPromptDay = -1;

	private RelicPrize openPrize;

	private Action restorePicker;

	private bool finishingRun;

	private bool resumeVictory;

	private bool claimedAtVictory;

	private static Plugin instance;

	private float nextOfferAt;

	private void Awake()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		patches = new Harmony("gkj.holdtheline");
		try
		{
			patches.PatchAll(typeof(Plugin).Assembly);
		}
		catch (Exception ex)
		{
			((Behaviour)this).enabled = false;
			patches.UnpatchSelf();
			((BaseUnityPlugin)this).Logger.LogError((object)("Hold the Line could not install its game hooks. " + ex));
			return;
		}
		instance = this;
		GameManager.OnGameInit += Reset;
		GameManager.BeforeStateChange += Transition;
		OverlayManager.OnOverlayClose += Closed;
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Hold the Line ready.");
	}

	private void OnDestroy()
	{
		instance = null;
		GameManager.OnGameInit -= Reset;
		GameManager.BeforeStateChange -= Transition;
		OverlayManager.OnOverlayClose -= Closed;
		Harmony obj = patches;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		Reset();
	}

	private void Reset()
	{
		Current = null;
		card = null;
		readySince = -1f;
		announced = null;
		claimPromptDay = -1;
		restorePicker?.Invoke();
		restorePicker = null;
		openPrize = null;
		finishingRun = (resumeVictory = (claimedAtVictory = false));
		nextOfferAt = 0f;
	}

	private static bool HasWall()
	{
		if ((Object)(object)WallManager.Instance != (Object)null && WallManager.Instance.HasWall() && WallManager.Instance.GetWallHitpoints() > 0f)
		{
			if (!CityManager.Instance.DidCityEventHappen((CityEvent)2))
			{
				return CityManager.Instance.DidCityEventHappen((CityEvent)17);
			}
			return true;
		}
		return false;
	}

	private static bool BeforeBattle(DaytimeManager clock)
	{
		if ((clock.IsMorning() || clock.IsDay()) && !CombatManager.Instance.IsCombat() && !CombatManager.Instance.IsCombatOver())
		{
			return CombatManager.Instance.CurrentMonstersAmount() == 0;
		}
		return false;
	}

	private void Update()
	{
		if (resumeVictory)
		{
			resumeVictory = false;
			if (claimedAtVictory && Current != null && Current.Unclaimed.Count > 0)
			{
				claimedAtVictory = false;
				OpenClaim(Current, Current.Unclaimed[0]);
			}
			else
			{
				OverlayManager.Instance.OpenGameOver(false);
				finishingRun = false;
			}
			return;
		}
		if (card != null)
		{
			if (card.Exists)
			{
				card.Refresh();
				return;
			}
			Closed();
		}
		GameManager val = GameManager.Instance;
		if ((Object)(object)val == (Object)null || !val.IsGameRunning() || val.IsGameOver() || val.IsUnloading())
		{
			return;
		}
		DaytimeManager val2 = DaytimeManager.Instance;
		string runID = GameDataManager.Instance.GetRunID();
		int num = val2.CurrentDay();
		bool flag = UIManager.Instance.IsWorldInteractable() && !DialogueManager.Instance.IsInDialogue();
		if (flag && Current?.Run == runID && Current.Unclaimed.Count > 0 && claimPromptDay != num && BeforeBattle(val2) && Time.unscaledTime >= nextOfferAt)
		{
			claimPromptDay = num;
			RelicPrize relicPrize = Current.Unclaimed.Find((RelicPrize p) => Array.Exists(p.Choices, (string id) => !RelicManager.Instance.HasRelic(id) && RelicManager.Instance.CanAddRelic(id)));
			if (relicPrize != null)
			{
				OpenClaim(Current, relicPrize);
				return;
			}
		}
		if (Current != null && announced != Current && Current.Run == runID && flag)
		{
			bool num2 = Current.Day == num - 1;
			bool flag2 = Current.Day == num && Current.State == Decision.Lost;
			if ((num2 || flag2) && ShowResult(Current, flag2))
			{
				announced = Current;
				nextOfferAt = Time.unscaledTime + 5f;
			}
		}
		if (!Wager.CanOffer(Current, runID, num, HasWall(), BeforeBattle(val2)) || !flag || Time.unscaledTime < nextOfferAt)
		{
			readySince = -1f;
			return;
		}
		if (readySince < 0f)
		{
			readySince = Time.unscaledTime;
		}
		if (!(Time.unscaledTime - readySince < 0.65f))
		{
			Wager wager = (Current = Wager.Open(Current, runID, num));
			string[] array = RelicRewards.Draw(wager);
			card = new OfferCard(num, array.Length == 3, delegate(int profit)
			{
				Accept(wager, profit);
			}, delegate
			{
				Accept(wager, 0);
			}, delegate
			{
				Close(wager);
			});
		}
	}

	private void OpenClaim(Wager wager, RelicPrize prize)
	{
		openPrize = prize;
		restorePicker = RelicRewards.Show(prize, finishingRun, delegate(string id)
		{
			if (Current == wager && openPrize == prize)
			{
				RelicManager relics = RelicManager.Instance;
				if (!relics.HasRelic(id) && relics.CanAddRelic(id) && wager.Claim(prize, id, delegate(string name)
				{
					try
					{
						return (Object)(object)relics.AddRelic(name) != (Object)null;
					}
					catch (Exception ex)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("Native relic grant interrupted: " + ex.Message));
						return relics.HasRelic(name);
					}
				}))
				{
					claimedAtVictory = finishingRun;
					OverlayManager.Instance.CloseOverlay(false);
					Notify(delegate
					{
						AlertManager.Instance.DisplayMessage("Hold the Line", "Relic claimed: " + ((Item)AddressablesManager.Instance.GetRelic(id)).GetTitle());
					});
				}
			}
		});
	}

	private void Accept(Wager wager, int profit)
	{
		if (card == null || Current != wager)
		{
			return;
		}
		GameManager val = GameManager.Instance;
		DaytimeManager val2 = DaytimeManager.Instance;
		ResourceManager purse = ResourceManager.Instance;
		if ((Object)(object)val == (Object)null || val.IsUnloading() || !val.IsGameRunning() || val.IsGameOver() || !wager.Matches(GameDataManager.Instance.GetRunID(), val2.CurrentDay()) || !HasWall() || !BeforeBattle(val2))
		{
			Close(wager);
			return;
		}
		bool flag;
		if (profit == 0)
		{
			string[] array = RelicRewards.Draw(wager);
			card.RefreshRelicOffer(array.Length == 3);
			flag = wager.AcceptRelic(array, purse.GetCoins(), (Action<int>)purse.AddToCoins);
		}
		else
		{
			flag = wager.AcceptCoin(profit, purse.GetCoins(), (Action<int>)purse.AddToCoins);
		}
		if (flag)
		{
			Notify(delegate
			{
				purse.ResourceAmountChanged((ResourceType)12);
			});
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Night {wager.Day}: {wager.Stake} coins staked on {wager.Kind}.");
			Close(wager);
		}
	}

	private void Close(Wager wager)
	{
		if (card != null && Current == wager)
		{
			OverlayManager.Instance.CloseOverlay(false);
		}
	}

	private void Closed()
	{
		if (openPrize != null)
		{
			restorePicker?.Invoke();
			restorePicker = null;
			openPrize = null;
			if (finishingRun)
			{
				resumeVictory = true;
			}
			nextOfferAt = Time.unscaledTime + 1f;
		}
		if (card != null)
		{
			Current?.Pass();
			card = null;
		}
	}

	private void Transition(GameState state)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Invalid comparison between Unknown and I4
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Invalid comparison between Unknown and I4
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Invalid comparison between Unknown and I4
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Invalid comparison between Unknown and I4
		//IL_010d: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Invalid comparison between Unknown and I4
		//IL_0111: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Invalid comparison between Unknown and I4
		bool flag = (int)state == 4 || (int)state == 6;
		if ((!flag && (int)state != 5 && (int)state != 7) || Current == null || !Current.Matches(GameDataManager.Instance.GetRunID(), DaytimeManager.Instance.CurrentDay()))
		{
			return;
		}
		ResourceManager resources = ResourceManager.Instance;
		bool survived = flag && (CombatManager.Instance.IsCombatOver() || DaytimeManager.Instance.IsNight());
		if (Current.Finish(survived, (Action<int>)resources.AddToCoins) && Current.State == Decision.Paid)
		{
			Notify(delegate
			{
				StatisticsManager.Instance.AddCoins(Current.Payout);
			});
			Notify(delegate
			{
				resources.ResourceAmountChanged((ResourceType)12);
			});
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Night {Current.Day}: paid {Current.Payout} coins.");
		}
		if (((int)state != 6 && (int)state != 5) || announced == Current)
		{
			return;
		}
		Notify(delegate
		{
			if (ShowResult(Current))
			{
				announced = Current;
			}
		});
	}

	private static bool ShowResult(Wager wager, bool wallHit = false)
	{
		if ((Object)(object)AlertManager.Instance == (Object)null)
		{
			return false;
		}
		string text;
		if (wager.State == Decision.Paid)
		{
			text = $"The wall held! {wager.Payout} coins paid (+{wager.Payout - wager.Stake} net).";
		}
		else
		{
			if (wager.State != Decision.Lost)
			{
				return false;
			}
			text = (wallHit ? $"Wall damaged! Your {wager.Stake} coin stake is lost." : $"Wager lost. Your {wager.Stake} coin stake is spent.");
		}
		AlertManager.Instance.DisplayMessage($"Hold the Line / Night {wager.Day}", text);
		return true;
	}

	private void Notify(Action publish)
	{
		try
		{
			publish();
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Wager recorded. Notification failed: " + ex.Message));
		}
	}
}
internal static class RelicRewards
{
	private static readonly HashSet<string> Ordinary = LoadNames();

	private static HashSet<string> LoadNames()
	{
		using StreamReader streamReader = new StreamReader(typeof(RelicRewards).Assembly.GetManifestResourceStream("HoldTheLine.OrdinaryRelics"));
		return new HashSet<string>(streamReader.ReadToEnd().Split(new char[2] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries), StringComparer.Ordinal);
	}

	internal static string[] Draw(Wager wager)
	{
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		RelicManager relics = RelicManager.Instance;
		HashSet<string> reserved = new HashSet<string>(wager.Unclaimed.SelectMany((RelicPrize p) => p.Choices));
		Races race = RaceManager.Instance.GetRace();
		HashSet<string> army = new HashSet<string>((from u in UnitManager.Instance.GetAllUnits()
			where (Object)(object)u != (Object)null
			select u).SelectMany(delegate(UnitBase u)
		{
			IEnumerable<string> relatedRelics = u.GetRelatedRelics();
			return relatedRelics ?? Enumerable.Empty<string>();
		}));
		IEnumerable<string> eligible = from id in (from r in AddressablesManager.Instance.GetAllRelics().Values
				where (Object)(object)r != (Object)null && Ordinary.Contains(((Object)r).name) && ((Item)r).GetIdentifier() == ((Object)r).name && !r.IsLaw() && !r.IsRacial() && !r.SoldAtCartographer() && ((int)((Item)r).GetKingdom() == 11 || ((Item)r).GetKingdom() == race) && r.GetRequiredKingdomLevel() <= RaceDataManager.Instance.GetKingdomLevel() && (string.IsNullOrEmpty(r.GetRelatedUnit()) || army.Contains(((Item)r).GetIdentifier()))
				select ((Item)r).GetIdentifier()).Distinct()
			where !reserved.Contains(id) && relics.IsUnlocked(id) && !relics.HasRelic(id) && relics.CanAddRelic(id)
			select id;
		return RelicPrize.Draw(wager.Run, wager.Day, eligible);
	}

	internal static Action Show(RelicPrize prize, bool finalNight, Action<string> claim)
	{
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Expected O, but got Unknown
		//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01da: Unknown result type (might be due to invalid IL or missing references)
		//IL_0203: Unknown result type (might be due to invalid IL or missing references)
		//IL_0246: Unknown result type (might be due to invalid IL or missing references)
		//IL_025c: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
		OverlayManager overlays = OverlayManager.Instance;
		UIOverlayMerchant merchantScreen = overlays.GetMerchantScreen();
		overlays.SetCanCloseOverlay(true);
		merchantScreen.Init("Relic Wager");
		merchantScreen.SetText($"Night {prize.Night} won. Choose one relic.");
		List<Button> list = new List<Button>();
		bool open = true;
		merchantScreen.SetUseCardSelectCallback(false);
		try
		{
			string[] choices = prize.Choices;
			foreach (string id in choices)
			{
				Relic relic = AddressablesManager.Instance.GetRelic(id);
				if ((Object)(object)relic == (Object)null)
				{
					continue;
				}
				UICardRelic component = merchantScreen.AddRelic(relic, (ResourceAmount[])null, -1, true, true).GetComponent<UICardRelic>();
				((UICard)component).AddCallback((UnityAction)delegate
				{
					if (open)
					{
						claim(id);
						if (open)
						{
							overlays.CloseOverlay(false);
						}
					}
				});
				Button cardButton = ((UICard)component).GetCardButton();
				((Selectable)cardButton).interactable = !RelicManager.Instance.HasRelic(id) && RelicManager.Instance.CanAddRelic(id);
				if (((Selectable)cardButton).interactable)
				{
					list.Add(cardButton);
				}
			}
		}
		finally
		{
			merchantScreen.SetUseCardSelectCallback(true);
		}
		TextMeshProUGUI cancelText = ((Component)((Component)merchantScreen).transform.Find("Panel/Buttons/Cancel/Button/Text")).GetComponent<TextMeshProUGUI>();
		LocalizeStringEvent localize = ((Component)cancelText).GetComponent<LocalizeStringEvent>();
		bool wasLocalized = (Object)(object)localize != (Object)null && ((Behaviour)localize).enabled;
		string previousText = ((TMP_Text)cancelText).text;
		if (wasLocalized)
		{
			((Behaviour)localize).enabled = false;
		}
		Transform val = merchantScreen.SetCancel(finalNight ? "Finish Run" : "Claim Later", (Action<UIOverlayMerchant>)null, false);
		Button cancel = ((Component)val).GetComponent<Button>();
		Navigation previousNavigation = ((Selectable)cancel).navigation;
		if (list.Count > 0)
		{
			Button val2 = list[list.Count / 2];
			Button obj = cancel;
			Navigation navigation = default(Navigation);
			((Navigation)(ref navigation)).mode = (Mode)4;
			((Navigation)(ref navigation)).selectOnUp = (Selectable)(object)val2;
			((Navigation)(ref navigation)).selectOnDown = (Selectable)(object)val2;
			((Navigation)(ref navigation)).selectOnLeft = (Selectable)(object)list[0];
			((Navigation)(ref navigation)).selectOnRight = (Selectable)(object)list[list.Count - 1];
			((Selectable)obj).navigation = navigation;
			for (int num = 0; num < list.Count; num++)
			{
				Button obj2 = list[num];
				navigation = default(Navigation);
				((Navigation)(ref navigation)).mode = (Mode)4;
				((Navigation)(ref navigation)).selectOnLeft = (Selectable)(object)list[(num + list.Count - 1) % list.Count];
				((Navigation)(ref navigation)).selectOnRight = (Selectable)(object)list[(num + 1) % list.Count];
				((Navigation)(ref navigation)).selectOnUp = (Selectable)(object)cancel;
				((Navigation)(ref navigation)).selectOnDown = (Selectable)(object)cancel;
				((Selectable)obj2).navigation = navigation;
			}
		}
		merchantScreen.Display();
		GamepadManager.Instance.SetGameObjectToSelect(((Component)val).gameObject, true);
		EventSystem current = EventSystem.current;
		if (current != null)
		{
			current.SetSelectedGameObject(((Component)val).gameObject);
		}
		return delegate
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			open = false;
			if ((Object)(object)cancel != (Object)null)
			{
				((Selectable)cancel).navigation = previousNavigation;
			}
			if ((Object)(object)cancelText != (Object)null)
			{
				((TMP_Text)cancelText).text = previousText;
			}
			if (wasLocalized && (Object)(object)localize != (Object)null)
			{
				((Behaviour)localize).enabled = true;
			}
		};
	}
}
internal static class SaveHooks
{
	[HarmonyPatch(typeof(GameDataManager), "PositionWorldBuildings")]
	internal static class WorldRead
	{
		private static void Prefix()
		{
			Begin();
		}

		private static void Postfix(GameData ___m_GameData)
		{
			Restore(___m_GameData);
		}

		private static void Finalizer()
		{
			End();
		}
	}

	[HarmonyPatch(typeof(TavernSaveManager), "Load")]
	internal static class TavernRead
	{
		private static void Prefix()
		{
			Begin();
		}

		private static void Finalizer()
		{
			End();
		}
	}

	[HarmonyPatch(typeof(SaveManager), "LoadGameData")]
	internal static class TavernData
	{
		private static void Postfix(GameData __result)
		{
			if (reading)
			{
				Restore(__result);
			}
		}
	}

	[HarmonyPatch]
	internal static class RawRead
	{
		private static MethodBase TargetMethod()
		{
			return AccessTools.FirstMethod(typeof(SaveManager), (Func<MethodInfo, bool>)((MethodInfo m) => m.Name == "Load" && !m.IsGenericMethod && m.ReturnType == typeof(string)));
		}

		private static void Postfix(string __0, string __result)
		{
			if (reading && IsGame(__0))
			{
				candidate = Checkpoint.Read(__result);
			}
		}
	}

	[HarmonyPatch(typeof(SaveManager), "Save", new Type[]
	{
		typeof(string),
		typeof(string)
	})]
	internal static class Write
	{
		private static void Prefix(string __0, ref string __1)
		{
			if (IsGame(__0))
			{
				__1 = Checkpoint.Attach(__1, Plugin.Current);
			}
		}
	}

	private static bool reading;

	private static Checkpoint.Header candidate;

	private static void Begin()
	{
		reading = true;
		candidate = null;
		Plugin.Current = null;
	}

	private static void End()
	{
		reading = false;
		candidate = null;
	}

	private static void Restore(GameData data)
	{
		Plugin.Current = ((data == null) ? null : Checkpoint.Restore(candidate, data.runID, data.hash));
	}

	private static bool IsGame(string path)
	{
		return path?.EndsWith("_game", StringComparison.Ordinal) ?? false;
	}
}
internal enum Decision
{
	Offered,
	Passed,
	Staked,
	Lost,
	Paid,
	RelicWon
}
internal enum WagerKind
{
	Coin,
	Relic
}
internal static class CoinTerms
{
	internal static bool Quote(int profit, out int stake, out int total)
	{
		stake = (total = 0);
		if (profit < 1)
		{
			return false;
		}
		long num = profit * ((long)profit + 1L) / 2;
		if (num + profit > int.MaxValue)
		{
			return false;
		}
		stake = (int)num;
		total = stake + profit;
		return true;
	}
}
internal sealed class RelicPrize
{
	public int Night { get; set; }

	public string[] Choices { get; set; }

	internal static string[] Draw(string run, int day, IEnumerable<string> eligible)
	{
		SHA256 hash = SHA256.Create();
		try
		{
			return eligible.Distinct<string>(StringComparer.Ordinal).OrderBy<string, string>((string id) => BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(run + "/" + day.ToString(CultureInfo.InvariantCulture) + "/" + id))), StringComparer.Ordinal).Take(3)
				.ToArray();
		}
		finally
		{
			if (hash != null)
			{
				((IDisposable)hash).Dispose();
			}
		}
	}

	internal static bool Valid(string[] choices)
	{
		if (choices != null && choices.Length == 3 && choices.All((string id) => !string.IsNullOrWhiteSpace(id)))
		{
			return choices.Distinct().Count() == 3;
		}
		return false;
	}
}
internal sealed class Wager
{
	internal const int RelicCost = 20;

	public string Run { get; set; }

	public int Day { get; set; }

	public Decision State { get; set; }

	public WagerKind Kind { get; set; }

	public int Stake { get; set; } = 1;

	public int Payout { get; set; } = 3;

	public string[] Choices { get; set; }

	public List<RelicPrize> Unclaimed { get; set; } = new List<RelicPrize>();

	internal bool Matches(string run, int day)
	{
		if (Run == run)
		{
			return Day == day;
		}
		return false;
	}

	internal static bool CanOffer(Wager previous, string run, int day, bool hasWall, bool beforeBattle)
	{
		if (!string.IsNullOrEmpty(run) && day > 0 && hasWall && beforeBattle)
		{
			if (previous != null && previous.Matches(run, day))
			{
				return previous.State == Decision.Offered;
			}
			return true;
		}
		return false;
	}

	internal static Wager Open(Wager previous, string run, int day)
	{
		if (previous != null && previous.Matches(run, day))
		{
			return previous;
		}
		return new Wager
		{
			Run = run,
			Day = day,
			Unclaimed = ((previous?.Run == run) ? previous.Unclaimed : new List<RelicPrize>())
		};
	}

	internal bool AcceptCoin(int profit, int coins, Action<int> changeCoins)
	{
		if (!CoinTerms.Quote(profit, out var stake, out var total) || coins < stake || (long)coins + (long)profit > int.MaxValue || State != Decision.Offered)
		{
			return false;
		}
		Stake = stake;
		Payout = total;
		Kind = WagerKind.Coin;
		return Charge(changeCoins);
	}

	internal bool AcceptRelic(string[] choices, int coins, Action<int> changeCoins)
	{
		if (State != Decision.Offered || coins < 20 || !RelicPrize.Valid(choices))
		{
			return false;
		}
		Stake = 20;
		Payout = 0;
		Kind = WagerKind.Relic;
		Choices = (string[])choices.Clone();
		return Charge(changeCoins);
	}

	private bool Charge(Action<int> changeCoins)
	{
		changeCoins(-Stake);
		State = Decision.Staked;
		return true;
	}

	internal void Pass()
	{
		if (State == Decision.Offered)
		{
			State = Decision.Passed;
		}
	}

	internal void Hit(float previous, float remaining)
	{
		if (State == Decision.Staked && remaining < previous)
		{
			State = Decision.Lost;
		}
	}

	internal bool Finish(bool survived, Action<int> changeCoins)
	{
		if (State != Decision.Staked)
		{
			return false;
		}
		if (!survived)
		{
			State = Decision.Lost;
			return false;
		}
		if (Kind == WagerKind.Relic)
		{
			Unclaimed.Add(new RelicPrize
			{
				Night = Day,
				Choices = Choices
			});
			State = Decision.RelicWon;
		}
		else
		{
			changeCoins(Payout);
			State = Decision.Paid;
		}
		return true;
	}

	internal bool Claim(RelicPrize prize, string id, Func<string, bool> grant)
	{
		if (prize == null || !prize.Choices.Contains(id) || !Unclaimed.Remove(prize))
		{
			return false;
		}
		if (grant(id))
		{
			return true;
		}
		Unclaimed.Insert(0, prize);
		return false;
	}
}
[HarmonyPatch(typeof(WallManager), "WallGetsHit")]
internal static class WallHit
{
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Expected O, but got Unknown
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: Expected O, but got Unknown
		List<CodeInstruction> list = instructions.ToList();
		FieldInfo hp = typeof(WallManager).GetField("m_Hitpoints", BindingFlags.Instance | BindingFlags.NonPublic) ?? throw new MissingFieldException(typeof(WallManager).FullName, "m_Hitpoints");
		List<CodeInstruction> list2 = list.FindAll((CodeInstruction i) => CodeInstructionExtensions.StoresField(i, hp));
		if (list2.Count != 1)
		{
			throw new InvalidOperationException("Expected one HP write in WallGetsHit. Wagers disabled.");
		}
		CodeInstruction val = list2[0];
		CodeInstruction val2 = CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), val);
		list.InsertRange(list.IndexOf(val), (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2]
		{
			val2,
			new CodeInstruction(OpCodes.Call, (object)new Func<float, WallManager, float>(Observe).Method)
		});
		return list;
	}

	private static float Observe(float remaining, WallManager wall)
	{
		Plugin.Current?.Hit(wall.GetWallHitpoints(), remaining);
		return remaining;
	}
}