Decompiled source of MineshaftUpgrades v0.1.9

plugins/MineshaftUpgrades.dll

Decompiled 27 minutes ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Buildings;
using SuperFantasyKingdom.UI;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
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("MineshaftUpgrades")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.9.0")]
[assembly: AssemblyInformationalVersion("0.1.9+00851a64fe8cedf09fc489b95d16a777dcb735d5")]
[assembly: AssemblyProduct("MineshaftUpgrades")]
[assembly: AssemblyTitle("MineshaftUpgrades")]
[assembly: AssemblyVersion("0.1.9.0")]
namespace MineshaftUpgrades;

internal static class MineArt
{
	private static readonly Dictionary<(Site, int), Sprite[]> Art = new Dictionary<(Site, int), Sprite[]>();

	private static readonly List<Texture2D> Textures = new List<Texture2D>();

	private static readonly HashSet<MineAppearance> Active = new HashSet<MineAppearance>();

	internal static void Load()
	{
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Expected O, but got Unknown
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		Assembly assembly = typeof(MineArt).Assembly;
		Site[] array = new Site[3]
		{
			Site.Stone,
			Site.Gold,
			Site.Ooze
		};
		foreach (Site site in array)
		{
			for (int j = 2; j <= 4; j++)
			{
				int num = ((site == Site.Ooze) ? 2 : 8);
				using Stream stream = assembly.GetManifestResourceStream($"MineshaftUpgrades.Art.{site}{j}.png");
				using MemoryStream memoryStream = new MemoryStream();
				if (stream == null)
				{
					throw new InvalidDataException($"Missing sprite atlas for {site} level {j}.");
				}
				stream.CopyTo(memoryStream);
				Texture2D val = new Texture2D(num * 32, 32, (TextureFormat)4, false)
				{
					filterMode = (FilterMode)0,
					wrapMode = (TextureWrapMode)1
				};
				Textures.Add(val);
				if (!ImageConversion.LoadImage(val, memoryStream.ToArray(), true) || ((Texture)val).width != num * 32 || ((Texture)val).height != 32)
				{
					throw new InvalidDataException($"Invalid sprite atlas for {site} level {j}.");
				}
				Sprite[] array2 = (Sprite[])(object)new Sprite[num];
				Art.Add((site, j), array2);
				for (int k = 0; k < array2.Length; k++)
				{
					array2[k] = Sprite.Create(val, new Rect((float)(k * 32), 0f, 32f, 32f), new Vector2(0.5f, 0.5f), 16f, 0u, (SpriteMeshType)0);
					((Object)array2[k]).name = $"MineshaftUpgrades.{site}.{j}.{k}";
				}
			}
		}
	}

	internal static void Apply(BuildingVein mine, Site site, int level)
	{
		MineAppearance mineAppearance = ((Component)mine).GetComponent<MineAppearance>();
		Sprite[] value;
		if (level == 1)
		{
			if ((Object)(object)mineAppearance != (Object)null)
			{
				mineAppearance.Restore();
			}
		}
		else if (Art.TryGetValue((site, level), out value) && !((Object)(object)((Building)mine).GetSpriteRenderer() == (Object)null))
		{
			if ((Object)(object)mineAppearance == (Object)null)
			{
				mineAppearance = ((Component)mine).gameObject.AddComponent<MineAppearance>();
				Active.Add(mineAppearance);
			}
			object obj;
			if (site != Site.Ooze)
			{
				obj = null;
			}
			else
			{
				Transform obj2 = ((Component)mine).transform.Find("Square");
				obj = ((obj2 != null) ? ((Component)obj2).GetComponent<SpriteRenderer>() : null);
			}
			SpriteRenderer wheel = (SpriteRenderer)obj;
			BuildingAnimator animator = ((site == Site.Ooze) ? null : ((Building)mine).GetBuildingAnimator());
			mineAppearance.SetTier(((Building)mine).GetSpriteRenderer(), value, animator, wheel);
		}
	}

	internal static void Forget(MineAppearance appearance)
	{
		Active.Remove(appearance);
	}

	internal static void Unload()
	{
		foreach (MineAppearance item in new List<MineAppearance>(Active))
		{
			if (!((Object)(object)item == (Object)null))
			{
				item.Restore();
				Object.Destroy((Object)(object)item);
			}
		}
		Active.Clear();
		foreach (Sprite[] value in Art.Values)
		{
			foreach (Sprite val in value)
			{
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
			}
		}
		Art.Clear();
		foreach (Texture2D texture in Textures)
		{
			Object.Destroy((Object)(object)texture);
		}
		Textures.Clear();
	}
}
public sealed class MineAppearance : MonoBehaviour
{
	private SpriteRenderer source;

	private SpriteRenderer poolWheel;

	private BuildingAnimator worker;

	private float? workStarted;

	private int nativeOrder;

	private int wheelOrder;

	private Sprite nativeFrame;

	private Sprite displayedFrame;

	private Sprite[] frames;

	internal void SetTier(SpriteRenderer target, Sprite[] sprites, BuildingAnimator animator, SpriteRenderer wheel)
	{
		if ((Object)(object)source != (Object)(object)target || (Object)(object)poolWheel != (Object)(object)wheel)
		{
			Restore();
			source = target;
			poolWheel = wheel;
		}
		if (frames == null && (Object)(object)poolWheel != (Object)null)
		{
			nativeOrder = ((Renderer)source).sortingOrder;
			wheelOrder = ((Renderer)poolWheel).sortingOrder;
		}
		if (frames != sprites || (Object)(object)worker != (Object)(object)animator)
		{
			workStarted = null;
		}
		worker = animator;
		frames = sprites;
		((Behaviour)this).enabled = true;
		LateUpdate();
	}

	private void LateUpdate()
	{
		if ((Object)(object)source == (Object)null || frames == null)
		{
			return;
		}
		if ((Object)(object)poolWheel != (Object)null)
		{
			if (((Renderer)source).sortingOrder != nativeOrder + 1)
			{
				((Renderer)source).sortingOrder = nativeOrder + 1;
			}
			if (((Renderer)poolWheel).sortingOrder != wheelOrder + 1)
			{
				((Renderer)poolWheel).sortingOrder = wheelOrder + 1;
			}
		}
		if ((Object)(object)source.sprite != (Object)(object)displayedFrame || (Object)(object)displayedFrame == (Object)null)
		{
			nativeFrame = source.sprite;
		}
		int num = 0;
		if (frames.Length == 2)
		{
			num = (int)(Time.time * 3f) & 1;
		}
		else if ((Object)(object)worker != (Object)null && ((Behaviour)worker).isActiveAndEnabled)
		{
			float valueOrDefault = workStarted.GetValueOrDefault();
			if (!workStarted.HasValue)
			{
				valueOrDefault = Time.time;
				workStarted = valueOrDefault;
			}
			num = (int)((Time.time - workStarted.Value) * 5f) % frames.Length;
		}
		else
		{
			workStarted = null;
		}
		displayedFrame = frames[num];
		if ((Object)(object)source.sprite != (Object)(object)displayedFrame)
		{
			source.sprite = displayedFrame;
		}
	}

	internal void Restore()
	{
		if ((Object)(object)source != (Object)null && (Object)(object)displayedFrame != (Object)null && (Object)(object)source.sprite == (Object)(object)displayedFrame)
		{
			source.sprite = nativeFrame;
		}
		if (frames != null && (Object)(object)poolWheel != (Object)null)
		{
			if ((Object)(object)source != (Object)null && ((Renderer)source).sortingOrder == nativeOrder + 1)
			{
				((Renderer)source).sortingOrder = nativeOrder;
			}
			if (((Renderer)poolWheel).sortingOrder == wheelOrder + 1)
			{
				((Renderer)poolWheel).sortingOrder = wheelOrder;
			}
		}
		nativeFrame = null;
		displayedFrame = null;
		workStarted = null;
		frames = null;
		((Behaviour)this).enabled = false;
	}

	private void OnDestroy()
	{
		Restore();
		MineArt.Forget(this);
	}
}
[HarmonyPatch(typeof(UIOverlayVariable), "Generate", new Type[]
{
	typeof(Building),
	typeof(List<UIBuildingOverlayElement>),
	typeof(string)
})]
internal static class AppendMineUpgrade
{
	private static void Prefix(Building building, ref List<UIBuildingOverlayElement> elements)
	{
		BuildingVein val = (BuildingVein)(object)((building is BuildingVein) ? building : null);
		if (val != null && Mines.CanUse(val))
		{
			elements = new List<UIBuildingOverlayElement>(elements);
			elements.Insert(0, (UIBuildingOverlayElement)(object)new MinePanel());
		}
	}
}
internal sealed class MinePanel : UIBuildingOverlayElement
{
	[Serializable]
	[CompilerGenerated]
	private sealed class <>c
	{
		public static readonly <>c <>9 = new <>c();

		public static UnityAction <>9__2_0;

		internal void <DrawTier>b__2_0()
		{
			OverlayManager.Instance.Cancel(true);
		}
	}

	public override GameObject Draw(Building building)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Expected O, but got Unknown
		BuildingVein mine = (BuildingVein)building;
		UIOverlayMessage component = Object.Instantiate<GameObject>(Resources.Load<GameObject>("UI/OverlayMessage"), ((UIBuildingOverlayElement)this).GetOverlaySelection()).GetComponent<UIOverlayMessage>();
		((Behaviour)((Component)component).GetComponent<Image>()).enabled = false;
		((Behaviour)((Component)component).GetComponent<ContentSizeFitter>()).enabled = false;
		((LayoutGroup)((Component)component).GetComponent<VerticalLayoutGroup>()).padding = new RectOffset();
		DrawTier(component, mine);
		return null;
	}

	private static string Benefit(BuildingVein mine, int level)
	{
		int num = Tier.TimeReduction(level);
		if (Mines.Kind(mine) != Site.Ooze)
		{
			if (num != 0)
			{
				return $"{num}% less extraction time";
			}
			return "Standard extraction time";
		}
		string resourcesTitle = ResourceManager.Instance.GetResourcesTitle((ResourceType)7, 0);
		if (((Building)mine).IsUpgraded())
		{
			if (num != 0)
			{
				return $"Connected cycle {num}% shorter";
			}
			return "Standard connected production time";
		}
		int num2 = Tier.Bonus(level);
		if (num2 != 0)
		{
			return $"Morning {resourcesTitle} +{num2}, storage +{num2}";
		}
		return "Standard morning yield";
	}

	private static void DrawTier(UIOverlayMessage panel, BuildingVein mine)
	{
		//IL_009a: 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_00a5: Expected O, but got Unknown
		//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e1: Expected O, but got Unknown
		//IL_020d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0206: Unknown result type (might be due to invalid IL or missing references)
		Tier tier = Mines.State(mine).Tier;
		int quoted = tier.Level;
		string text = $"Level {quoted}/{4}";
		string text2 = Benefit(mine, quoted);
		Button component = ((Component)((Component)panel).transform.Find("Buttons/Cancel")).GetComponent<Button>();
		UIOverlayMessage obj = panel;
		object obj2 = <>c.<>9__2_0;
		if (obj2 == null)
		{
			UnityAction val = delegate
			{
				OverlayManager.Instance.Cancel(true);
			};
			<>c.<>9__2_0 = val;
			obj2 = (object)val;
		}
		obj.SetCancel("", (UnityAction)obj2);
		if (quoted == 4)
		{
			panel.SetMessage("<color=#FFF0D4>" + text + " (Max level)\n" + text2 + "</color>");
			panel.RemoveAccept();
			GamepadManager.Instance.SetGameObjectToSelect(((Component)component).gameObject, true);
			return;
		}
		int num = Tier.Price(quoted);
		string resourcesTitle = ResourceManager.Instance.GetResourcesTitle((ResourceType)3, 0);
		bool flag = tier.CanBuy(quoted, Mines.Spendable());
		string text3 = (flag ? "" : ("\nNot enough " + resourcesTitle));
		panel.SetMessage("<color=#FFF0D4>" + text + "\n" + text2 + "\n" + $"Next  {Benefit(mine, quoted + 1)}\nCost  {num} {resourcesTitle}{text3}</color>");
		Button val2 = panel.SetAccept(new ResourceAmount((ResourceType)3, num), (UnityAction)delegate
		{
			if (!((Object)(object)panel == (Object)null) && ((Component)panel).gameObject.activeInHierarchy)
			{
				if (Mines.TryPurchase(mine, quoted))
				{
					OverlayManager.Instance.Confirm();
				}
				else if (Mines.CanUse(mine))
				{
					DrawTier(panel, mine);
				}
			}
		}, false);
		((Selectable)val2).interactable = flag;
		((Graphic)((Component)((Component)val2).transform.Find("Amount")).GetComponent<TextMeshProUGUI>()).color = (flag ? Color.white : Color.red);
		GamepadManager.Instance.SetGameObjectToSelect(((Component)(flag ? val2 : component)).gameObject, true);
	}
}
[HarmonyPatch(typeof(BuildingCity), "GetQueue", new Type[] { })]
internal static class SaveMineTier
{
	private static void Postfix(BuildingCity __instance, ref List<int> __result)
	{
		if (__result == null)
		{
			BuildingVein val = (BuildingVein)(object)((__instance is BuildingVein) ? __instance : null);
			if (val != null && Mines.Kind(val) != Site.None)
			{
				__result = Mines.State(val).Tier.Save();
			}
		}
	}
}
[HarmonyPatch(typeof(BuildingResource), "SetQueue", new Type[] { typeof(List<int>) })]
internal static class RestoreMineTier
{
	private static void Postfix(BuildingResource __instance, List<int> queue)
	{
		BuildingVein val = (BuildingVein)(object)((__instance is BuildingVein) ? __instance : null);
		if (val != null && Mines.Kind(val) != Site.None)
		{
			MineState mineState = Mines.State(val);
			mineState.Tier.Restore(queue);
			mineState.Apply(val);
		}
	}
}
[HarmonyPatch(typeof(BuildingVein), "GetWorkTimeMultiplier", new Type[] { })]
internal static class MineWorkDuration
{
	private static void Postfix(BuildingVein __instance, ref float __result)
	{
		Site site = Mines.Kind(__instance);
		if (site == Site.Stone || site == Site.Gold)
		{
			__result *= Tier.DurationFactor(Mines.State(__instance).Tier.Level);
		}
	}
}
[HarmonyPatch(typeof(BuildingVeinGenerateMorning), "OnMorningStart", new Type[] { typeof(int) })]
internal static class OozeProduction
{
	private static readonly Dictionary<BuildingVeinGenerateMorning, BuildingCity> Links = new Dictionary<BuildingVeinGenerateMorning, BuildingCity>();

	private static void Postfix(BuildingVeinGenerateMorning __instance, int obj)
	{
		//IL_0041: 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)
		if (Mines.Kind((BuildingVein)(object)__instance) != Site.Ooze || ((Building)__instance).IsUpgraded())
		{
			return;
		}
		ResourceStorage storage = ((Building)__instance).GetStorage();
		Tier tier = Mines.State((BuildingVein)(object)__instance).Tier;
		int space = storage.SpaceForResource((ResourceType)7, false);
		int num = tier.ClaimMorningBonus(obj, space);
		for (int i = 0; i < num; i++)
		{
			ResourcePacket val = ((Building)__instance).GenerateResource((ResourceType)7, Vector2.op_Implicit(((Component)__instance).transform.position), 1, false);
			if (val != null)
			{
				JobManager.Instance.RegisterCarryJob((BuildingCity)(object)__instance, val, (BuildingCity)null);
			}
		}
	}

	internal static void Remember(BuildingVeinGenerateMorning pool, BuildingCity target)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Invalid comparison between Unknown and I4
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Invalid comparison between Unknown and I4
		if ((Object)(object)target != (Object)null && Mines.Kind((BuildingVein)(object)pool) == Site.Ooze && target is BuildingGeneratingg && (int)((Building)target).GetBuildingType() == 7 && (int)((Building)target).GetResource() == 7)
		{
			Links[pool] = target;
		}
	}

	internal static void Forget(BuildingVeinGenerateMorning pool)
	{
		Links.Remove(pool);
	}

	internal static void Clear()
	{
		Links.Clear();
	}

	internal static int LinkedLevel(BuildingGeneratingg target)
	{
		int num = 1;
		foreach (KeyValuePair<BuildingVeinGenerateMorning, BuildingCity> link in Links)
		{
			BuildingVeinGenerateMorning key = link.Key;
			if ((Object)(object)link.Value == (Object)(object)target && (Object)(object)key != (Object)null && ((Behaviour)key).isActiveAndEnabled && ((Building)key).IsUpgraded() && !((BuildingCity)key).ShouldRemove())
			{
				num = Math.Max(num, Mines.State((BuildingVein)(object)key).Tier.Level);
			}
		}
		return num;
	}
}
[HarmonyPatch(typeof(BuildingVeinGenerateMorning), "Upgrade", new Type[]
{
	typeof(int),
	typeof(bool)
})]
internal static class LinkOozePool
{
	private static void Postfix(BuildingVeinGenerateMorning __instance, BuildingCity ___m_Target)
	{
		OozeProduction.Remember(__instance, ___m_Target);
	}
}
[HarmonyPatch(typeof(BuildingVeinGenerateMorning), "OnDestroy", new Type[] { })]
internal static class UnlinkOozePool
{
	private static void Postfix(BuildingVeinGenerateMorning __instance)
	{
		OozeProduction.Forget(__instance);
	}
}
[HarmonyPatch(typeof(BuildingGeneratingg), "GetGenerationDuration", new Type[] { })]
internal static class ConnectedOozeDuration
{
	private static void Postfix(BuildingGeneratingg __instance, ref float __result)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Invalid comparison between Unknown and I4
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Invalid comparison between Unknown and I4
		if ((int)((Building)__instance).GetBuildingType() == 7 && (int)((Building)__instance).GetResource() == 7)
		{
			__result *= Tier.DurationFactor(OozeProduction.LinkedLevel(__instance));
		}
	}
}
[BepInPlugin("gkj.sfk.mineshaftupgrades", "Mineshaft Upgrades", "0.1.9")]
public sealed class Plugin : BaseUnityPlugin
{
	internal const string Id = "gkj.sfk.mineshaftupgrades";

	private static readonly Guid SupportedBuild = new Guid("da6b1cd7-6dac-4d65-8647-db23f22f811b");

	private Harmony harmony;

	internal static Plugin Instance { get; private set; }

	private void Awake()
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Expected O, but got Unknown
		if (typeof(BuildingVein).Module.ModuleVersionId != SupportedBuild)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"Mineshaft Upgrades requires the verified Super Fantasy Kingdom 0.8.070 assembly.");
			return;
		}
		try
		{
			MineArt.Load();
			harmony = new Harmony("gkj.sfk.mineshaftupgrades");
			harmony.PatchAll(typeof(Plugin).Assembly);
			Instance = this;
		}
		catch (Exception ex)
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			MineArt.Unload();
			((BaseUnityPlugin)this).Logger.LogError((object)ex);
		}
	}

	internal void Warn(Exception error)
	{
		((BaseUnityPlugin)this).Logger.LogWarning((object)error);
	}

	private void OnDestroy()
	{
		Instance = null;
		Harmony obj = harmony;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		OozeProduction.Clear();
		MineArt.Unload();
	}
}
internal enum Site
{
	None,
	Stone,
	Gold,
	Ooze
}
internal static class Mines
{
	internal const ResourceType Currency = (ResourceType)3;

	private static readonly ConditionalWeakTable<BuildingVein, MineState> States = new ConditionalWeakTable<BuildingVein, MineState>();

	internal static Site Kind(BuildingVein mine)
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Invalid comparison between Unknown and I4
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: 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_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Invalid comparison between Unknown and I4
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Invalid comparison between Unknown and I4
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Invalid comparison between Unknown and I4
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Invalid comparison between Unknown and I4
		if ((Object)(object)mine == (Object)null || (Object)(object)RaceManager.Instance == (Object)null || (int)((Building)mine).GetBuildingType() != 20)
		{
			return Site.None;
		}
		string text = ((Object)mine).name;
		if (text.EndsWith("(Clone)", StringComparison.Ordinal))
		{
			text = text.Substring(0, text.Length - "(Clone)".Length).TrimEnd();
		}
		Races race = RaceManager.Instance.GetRace();
		if ((int)race != 0)
		{
			if ((int)race == 2 && ((object)mine).GetType() == typeof(BuildingVeinGenerateMorning) && text == "UndeadSewageVein" && (int)((Building)mine).GetResource() == 7)
			{
				return Site.Ooze;
			}
		}
		else if (((object)mine).GetType() == typeof(BuildingVein))
		{
			if (text == "HumanStoneVein" && (int)((Building)mine).GetResource() == 4)
			{
				return Site.Stone;
			}
			if (text == "HumanGoldVein" && (int)((Building)mine).GetResource() == 15)
			{
				return Site.Gold;
			}
		}
		return Site.None;
	}

	internal static MineState State(BuildingVein mine)
	{
		return States.GetValue(mine, (BuildingVein _) => new MineState());
	}

	internal static bool CanUse(BuildingVein mine)
	{
		if ((Object)(object)Plugin.Instance != (Object)null && (Object)(object)mine != (Object)null && (Object)(object)GameManager.Instance != (Object)null && GameManager.Instance.IsGameLoaded() && ((Behaviour)mine).isActiveAndEnabled && !((BuildingCity)mine).ShouldRemove())
		{
			return Kind(mine) != Site.None;
		}
		return false;
	}

	internal static int Spendable()
	{
		ResourceStorage storage;
		return GetPaymentPackets(Tier.Price(3), out storage).Count;
	}

	internal static bool TryPurchase(BuildingVein mine, int quotedLevel)
	{
		if (!CanUse(mine) || quotedLevel < 1 || quotedLevel >= 4 || (Object)(object)ResourceManager.Instance == (Object)null)
		{
			return false;
		}
		MineState mineState = State(mine);
		ResourceStorage storage;
		List<ResourcePacket> packets = GetPaymentPackets(Tier.Price(quotedLevel), out storage);
		if (!mineState.Tier.TryBuy(quotedLevel, packets.Count, (int price) => Debit(storage, packets, price)))
		{
			return false;
		}
		mineState.Apply(mine);
		try
		{
			ResourceManager.Instance.ResourceAmountChanged((ResourceType)3);
		}
		catch (Exception error)
		{
			Plugin.Instance?.Warn(error);
		}
		return true;
	}

	private static List<ResourcePacket> GetPaymentPackets(int limit, out ResourceStorage storage)
	{
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: 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)
		//IL_0038: Invalid comparison between Unknown and I4
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: Invalid comparison between Unknown and I4
		List<ResourcePacket> list = new List<ResourcePacket>(limit);
		storage = null;
		if ((Object)(object)RaceManager.Instance == (Object)null || (Object)(object)CityManager.Instance == (Object)null)
		{
			return list;
		}
		BuildingType buildingTypeToTakeFrom = RaceManager.Instance.GetBuildingTypeToTakeFrom((ResourceType)3);
		if ((int)buildingTypeToTakeFrom == 666)
		{
			return list;
		}
		BuildingCity building = CityManager.Instance.GetBuilding(buildingTypeToTakeFrom);
		if ((Object)(object)building == (Object)null)
		{
			return list;
		}
		storage = ((Building)building).GetStorage();
		if ((Object)(object)storage == (Object)null || !storage.ShouldGenerateResourcePackets())
		{
			return list;
		}
		List<ResourcePacket> allResourcePackets = storage.GetAllResourcePackets();
		int num = allResourcePackets.Count - 1;
		while (num >= 0 && list.Count < limit)
		{
			ResourcePacket val = allResourcePackets[num];
			if (!val.IsReserved() && (int)val.GetResourceType() == 3 && val.GetAmount() == 1)
			{
				list.Add(val);
			}
			num--;
		}
		return list;
	}

	private static bool Debit(ResourceStorage storage, List<ResourcePacket> packets, int price)
	{
		List<ResourcePacket> list = new List<ResourcePacket>(price);
		foreach (ResourcePacket packet in packets)
		{
			ResourcePacket val = storage.TakeResourcePacket(packet.GetIdentifier(), false);
			if (val == null)
			{
				foreach (ResourcePacket item in list)
				{
					storage.AddResourcePacket(item, false);
				}
				return false;
			}
			list.Add(val);
		}
		return true;
	}
}
internal sealed class MineState
{
	private int? nativeOozeCapacity;

	internal Tier Tier { get; } = new Tier();

	internal void Apply(BuildingVein mine)
	{
		Site site = Mines.Kind(mine);
		if (site == Site.Ooze)
		{
			ResourceStorage storage = ((Building)mine).GetStorage();
			if ((Object)(object)storage != (Object)null)
			{
				nativeOozeCapacity = nativeOozeCapacity ?? storage.GetStorageSpace((ResourceType)7);
				storage.SetStorageSpace((ResourceType)7, nativeOozeCapacity.Value + Tier.Level - 1);
			}
		}
		MineArt.Apply(mine, site, Tier.Level);
	}
}
internal sealed class Tier
{
	internal const int MaxLevel = 4;

	private const int QueueMarker = 1297306881;

	private static readonly int[] Prices = new int[4] { 8, 16, 32, 0 };

	private static readonly int[] TimeReductions = new int[4] { 0, 10, 25, 50 };

	private int lastBonusMorning = -1;

	internal int Level { get; private set; } = 1;

	internal static int Price(int level)
	{
		return Prices[level - 1];
	}

	internal static int Bonus(int level)
	{
		return level - 1;
	}

	internal static int TimeReduction(int level)
	{
		return TimeReductions[level - 1];
	}

	internal static float DurationFactor(int level)
	{
		return (float)(100 - TimeReduction(level)) / 100f;
	}

	internal bool CanBuy(int quotedLevel, int spendable)
	{
		if (quotedLevel == Level && Level < 4)
		{
			return spendable >= Price(Level);
		}
		return false;
	}

	internal bool TryBuy(int quotedLevel, int spendable, Func<int, bool> debit)
	{
		if (!CanBuy(quotedLevel, spendable) || !debit(Price(Level)))
		{
			return false;
		}
		Level++;
		return true;
	}

	internal int ClaimMorningBonus(int day, int space)
	{
		if (day <= lastBonusMorning || Level == 1)
		{
			return 0;
		}
		lastBonusMorning = day;
		return Math.Max(0, Math.Min(Bonus(Level), space));
	}

	internal List<int> Save()
	{
		if (Level != 1)
		{
			return new List<int> { 1297306881, Level, lastBonusMorning };
		}
		return null;
	}

	internal void Restore(List<int> queue)
	{
		bool flag = queue != null && queue.Count == 3 && queue[0] == 1297306881 && queue[1] >= 2 && queue[1] <= 4 && queue[2] >= -1;
		Level = ((!flag) ? 1 : queue[1]);
		lastBonusMorning = (flag ? queue[2] : (-1));
	}
}