Decompiled source of WantedExtensions v0.1.9

plugins/WantedExtensions/WantedExtensions.dll

Decompiled a day ago
using System;
using System.Collections;
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.ExceptionServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using UnityEngine;
using WantedExtensions.Core;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("WantedExtensions")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.9.0")]
[assembly: AssemblyInformationalVersion("0.1.9+a3650a2b2d1ea612c82eb6899b3ca539db0c671d")]
[assembly: AssemblyProduct("WantedExtensions")]
[assembly: AssemblyTitle("WantedExtensions")]
[assembly: AssemblyVersion("0.1.9.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 WantedExtensions
{
	internal sealed class Wire
	{
		public string Action = "";

		public string Id = "";

		public long PlayerUser;

		public uint PlayerObject;

		public string Character = "";

		public long World;

		public Transaction? Transaction;

		public string Message = "";
	}
	internal sealed class BoardState
	{
		public Transaction? Active;

		public List<Transaction> History = new List<Transaction>();
	}
	public sealed class BoardAgent : MonoBehaviour
	{
		internal const string WidthKey = "WantedExtensions.width";

		internal const string HeightKey = "WantedExtensions.height";

		private const string StateKey = "WantedExtensions.transactions.v1";

		private const string Rpc = "friends.valheim.wantedextensions.Board.v1";

		private ZNetView view;

		private Container box;

		private readonly Random random = new Random();

		private float nextTick;

		private float nextQuota;

		private string? quotaWarning;

		private bool registered;

		private readonly HashSet<string> compatibilityProblems = new HashSet<string>();

		internal bool IsAvailable
		{
			get
			{
				if ((Object)(object)view != (Object)null)
				{
					return view.IsValid();
				}
				return false;
			}
		}

		internal ZDOID Id => view.GetZDO().m_uid;

		internal long Owner => view.GetZDO().GetOwner();

		internal bool Busy
		{
			get
			{
				if ((Object)(object)view == (Object)null || !view.IsValid())
				{
					return false;
				}
				try
				{
					return State().Active?.Busy(Plugin.Now) ?? false;
				}
				catch
				{
					return true;
				}
			}
		}

		private string Notices => view.GetZDO().GetString("Wanted.notices", "");

		private void Awake()
		{
			view = ((Component)this).GetComponent<ZNetView>();
			box = ((Component)this).GetComponent<Container>();
			Plugin.Boards.Add(this);
			Register();
		}

		private void Register()
		{
			if (!registered && !((Object)(object)view == (Object)null) && view.IsValid())
			{
				view.Register<string>("friends.valheim.wantedextensions.Board.v1", (Action<long, string>)OnRpc);
				registered = true;
				Resize();
			}
		}

		private void OnDestroy()
		{
			Plugin.Boards.Remove(this);
			if (registered && (Object)(object)view != (Object)null)
			{
				view.Unregister("friends.valheim.wantedextensions.Board.v1");
			}
		}

		internal bool TryOpenReply(out string reply)
		{
			reply = "";
			if (!IsAvailable)
			{
				return false;
			}
			try
			{
				reply = Compatibility.OpenReply(box, view) ?? "";
			}
			catch (Exception ex)
			{
				ReportCompatibility("Could not inspect chest-open RPC: " + ex.Message);
			}
			return reply.Length > 0;
		}

		internal bool CanPurchase(out string problem)
		{
			if (!IsAvailable)
			{
				problem = "Board is not ready.";
				return false;
			}
			string text = Rules.RequestProblem(Compatibility.Count(Notices), Compatibility.MaxNotices());
			if (text != null)
			{
				problem = text;
				return false;
			}
			problem = InventoryApi.Problem ?? "";
			if (problem.Length == 0 && !TryOpenReply(out string _))
			{
				problem = "Unrecognised chest-open response; check the BepInEx log.";
			}
			if (problem.Length > 0)
			{
				ReportCompatibility(problem);
				return false;
			}
			return true;
		}

		private void ReportCompatibility(string problem)
		{
			if (compatibilityProblems.Add(problem))
			{
				Plugin.Warn("Wanted reroll compatibility: " + problem);
			}
		}

		private BoardState State()
		{
			string text = view.GetZDO().GetString("WantedExtensions.transactions.v1", "");
			return (text.Length == 0) ? new BoardState() : (Json.Read<BoardState>(text) ?? throw new InvalidOperationException("Invalid board transaction state."));
		}

		private void Save(BoardState state)
		{
			view.GetZDO().Set("WantedExtensions.transactions.v1", Json.Write(state));
		}

		internal void Resize()
		{
			if ((Object)(object)box == (Object)null || (Object)(object)view == (Object)null || !view.IsValid() || Plugin.Effective == null)
			{
				return;
			}
			RerollSettings effective = Plugin.Effective;
			Inventory inventory = box.GetInventory();
			if (inventory != null && !box.IsInUse())
			{
				List<ItemData> allItems = inventory.GetAllItems();
				int num = effective.Columns;
				int num2 = effective.Rows;
				if (!Rules.Fits(num, num2, allItems.Select((ItemData i) => (x: i.m_gridPos.x, y: i.m_gridPos.y))))
				{
					num = Math.Max(num, inventory.GetWidth());
					num2 = Math.Max(num2, inventory.GetHeight());
				}
				if (inventory.GetWidth() != num || inventory.GetHeight() != num2)
				{
					AccessTools.Field(typeof(Inventory), "m_width").SetValue(inventory, num);
					AccessTools.Field(typeof(Inventory), "m_height").SetValue(inventory, num2);
					box.m_width = num;
					box.m_height = num2;
				}
				if (view.IsOwner())
				{
					view.GetZDO().Set("WantedExtensions.width", num);
					view.GetZDO().Set("WantedExtensions.height", num2);
				}
			}
		}

		private void Update()
		{
			if (Time.unscaledTime < nextTick)
			{
				return;
			}
			nextTick = Time.unscaledTime + 0.5f;
			try
			{
				Register();
				if (!registered || !view.IsOwner())
				{
					return;
				}
				BoardState boardState = State();
				Transaction active = boardState.Active;
				if (active == null)
				{
					return;
				}
				if ((active.State == "prepared" || active.State == "reserving") && Plugin.Now >= active.Expires)
				{
					if (active.State == "reserving")
					{
						active.CooldownUntil = 0.0;
					}
					active.State = "cancelled";
					active.Reason = "Reroll reservation expired. No reroll applied.";
					Save(boardState);
				}
				if (active.NeedsDailyQuota && !active.QuotaSettled && Time.unscaledTime >= nextQuota)
				{
					nextQuota = Time.unscaledTime + 2f;
					if (active.State == "reserving")
					{
						DailyLimits.Send(this, active, "reserve");
					}
					else if (active.State == "committing")
					{
						DailyLimits.Send(this, active, "commit");
					}
					else if (active.State == "cancelled")
					{
						DailyLimits.Send(this, active, "release");
					}
				}
			}
			catch (Exception e)
			{
				Plugin.Error(e);
			}
		}

		internal void Request()
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			if (!registered)
			{
				Plugin.Tell("Board is not ready.");
				return;
			}
			RerollSettings effective = Plugin.Effective;
			string problem;
			if (effective == null)
			{
				Plugin.Tell("Waiting for Wanted Extensions on the server.");
			}
			else if (!effective.Enabled)
			{
				Plugin.Tell("Paid rerolls are disabled by the server.");
			}
			else if (!CanPurchase(out problem))
			{
				Plugin.Tell(problem + " No payment taken.");
			}
			else if (Busy)
			{
				Plugin.Tell("Someone is rerolling this board. Please wait.");
			}
			else if (box.IsInUse())
			{
				Plugin.Tell("Someone is using this board's chest. Please wait.");
			}
			else if (Payments.PendingFor(Id))
			{
				Plugin.Tell("Your previous reroll is still being checked. Please wait.");
			}
			else
			{
				Payments.Begin(this, effective);
			}
		}

		internal void SendToOwner(Wire message)
		{
			view.InvokeRPC("friends.valheim.wantedextensions.Board.v1", new object[1] { Json.Write(message) });
		}

		private void Reply(long peer, string action, string id, Transaction? transaction = null, string message = "")
		{
			view.InvokeRPC(peer, "friends.valheim.wantedextensions.Board.v1", new object[1] { Json.Write(new Wire
			{
				Action = action,
				Id = id,
				Transaction = transaction,
				Message = message
			}) });
		}

		internal void WarnPeer(long peer)
		{
			Reply(peer, "warning", Guid.NewGuid().ToString("N"), null, "Someone is rerolling this board. Please wait.");
		}

		private bool Authentic(long sender, Wire message, bool requireNearby)
		{
			//IL_0034: 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_0081: Unknown result type (might be due to invalid IL or missing references)
			if (message.World != ZNet.instance.GetWorldUID() || message.Character.Length > 30)
			{
				return false;
			}
			ZDO zDO = ZDOMan.instance.GetZDO(new ZDOID(message.PlayerUser, message.PlayerObject));
			if (zDO != null && zDO.GetOwner() == sender && zDO.GetLong("playerID", 0L).ToString(CultureInfo.InvariantCulture) == message.Character)
			{
				if (requireNearby)
				{
					return Vector3.Distance(zDO.GetPosition(), ((Component)this).transform.position) <= 6f;
				}
				return true;
			}
			return false;
		}

		private void OnRpc(long sender, string json)
		{
			if (json.Length > 131072)
			{
				return;
			}
			try
			{
				Wire wire = Json.Read<Wire>(json);
				if (wire == null || !Guid.TryParseExact(wire.Id, "N", out var _))
				{
					return;
				}
				if (wire.Action == "warning")
				{
					if (sender == view.GetZDO().GetOwner())
					{
						Plugin.Tell(wire.Message);
					}
				}
				else if (wire.Action == "offer" || wire.Action == "result" || wire.Action == "rejected")
				{
					if (sender == view.GetZDO().GetOwner())
					{
						Payments.OnReply(this, wire);
					}
				}
				else if (view.IsOwner() && Authentic(sender, wire, wire.Action == "request"))
				{
					BoardState state = State();
					if (wire.Action == "request")
					{
						Prepare(sender, wire, state);
					}
					else if (wire.Action == "paid" || wire.Action == "declined" || wire.Action == "query")
					{
						Finish(sender, wire, state);
					}
				}
			}
			catch (Exception e)
			{
				Plugin.Error(e);
			}
		}

		private void Prepare(long sender, Wire message, BoardState state)
		{
			Transaction transaction = Find(state, message.Id);
			if (transaction != null)
			{
				if (transaction.PlayerId == message.Character)
				{
					Reply(sender, (transaction.State == "prepared") ? "offer" : "result", message.Id, transaction);
				}
				return;
			}
			RerollSettings effective = Plugin.Effective;
			if (effective == null || !effective.Enabled)
			{
				Reply(sender, "rejected", message.Id, null, "Rerolls are unavailable; waiting for valid server settings.");
				return;
			}
			if (!CanPurchase(out string problem))
			{
				Reply(sender, "rejected", message.Id, null, problem + " No payment taken.");
				return;
			}
			Transaction? active = state.Active;
			if (active != null && active.Busy(Plugin.Now))
			{
				Reply(sender, "rejected", message.Id, null, "Someone is rerolling this board. Please wait.");
				return;
			}
			Transaction? active2 = state.Active;
			if (active2 != null && active2.NeedsDailyQuota && !state.Active.QuotaSettled)
			{
				Reply(sender, "rejected", message.Id, null, "The previous daily-limit reservation is still being settled. Please wait.");
				return;
			}
			if (box.IsInUse())
			{
				Reply(sender, "rejected", message.Id, null, "Someone is using this board's chest. Please wait.");
				return;
			}
			GameObject prefab = ZNetScene.instance.GetPrefab(effective.CostItem);
			if ((Object)(object)prefab == (Object)null || (Object)(object)prefab.GetComponent<ItemDrop>() == (Object)null)
			{
				Reply(sender, "rejected", message.Id, null, "The server's reroll payment item is invalid. Ask an admin to check CostItem.");
				return;
			}
			string notices = Notices;
			int num = Compatibility.Count(notices);
			int maximum = Compatibility.MaxNotices();
			string text = Rules.RequestProblem(num, maximum);
			if (text != null)
			{
				Reply(sender, "rejected", message.Id, null, text);
				return;
			}
			int num2 = Rules.RollCount(num, maximum, effective, random.Next(100));
			string text2 = Compatibility.Generate(num2, random);
			if (Compatibility.Count(text2) != num2 || Rules.CountChangeProblem(num, num2, maximum) != null)
			{
				Reply(sender, "rejected", message.Id, null, "Could not generate the requested notice count. No payment taken.");
				return;
			}
			if (state.Active != null)
			{
				if (state.Active.State == "prepared")
				{
					state.Active.Decide(Plugin.Now, notices, paid: false, box.IsInUse());
				}
				state.Active.Before = "";
				state.Active.After = "";
				state.History.Add(state.Active);
				if (state.History.Count > 64)
				{
					state.History.RemoveAt(0);
				}
			}
			state.Active = new Transaction
			{
				Id = message.Id,
				PlayerPeer = sender,
				PlayerId = message.Character,
				Before = notices,
				After = text2,
				BeforeCount = num,
				AfterCount = num2,
				CostItem = effective.CostItem,
				CostAmount = effective.CostAmount,
				NeedsDailyQuota = true,
				State = "reserving",
				PlayerObjectUser = message.PlayerUser,
				PlayerObjectId = message.PlayerObject,
				Expires = Plugin.Now + 15.0,
				CooldownUntil = Plugin.Now + effective.CooldownSeconds
			};
			Save(state);
			nextQuota = Time.unscaledTime + 2f;
			DailyLimits.Send(this, state.Active, "reserve");
		}

		private static Transaction? Find(BoardState state, string id)
		{
			if (!(state.Active?.Id == id))
			{
				return state.History.FirstOrDefault((Transaction t) => t.Id == id);
			}
			return state.Active;
		}

		private void Finish(long sender, Wire message, BoardState state)
		{
			Transaction transaction = Find(state, message.Id);
			if (transaction == null)
			{
				Reply(sender, "result", message.Id, null, "Outcome unavailable. Payment receipt retained; ask an admin to check before any refund.");
			}
			else
			{
				if (transaction.PlayerId != message.Character)
				{
					return;
				}
				if (transaction.State == "prepared" && message.Action != "query")
				{
					if (transaction.Decide(Plugin.Now, Notices, message.Action == "paid", box.IsInUse(), Compatibility.MaxNotices(), Compatibility.Count) == "committed")
					{
						if (transaction.NeedsDailyQuota)
						{
							transaction.State = "committing";
							Save(state);
							nextQuota = Time.unscaledTime + 2f;
							DailyLimits.Send(this, transaction, "commit");
							return;
						}
						Save(state);
						Publish(transaction);
					}
					else
					{
						Save(state);
						if (transaction.NeedsDailyQuota && !transaction.QuotaSettled)
						{
							DailyLimits.Send(this, transaction, "release");
						}
					}
				}
				else if (transaction.State == "committed" && Notices == transaction.Before && state.Active == transaction)
				{
					Publish(transaction);
				}
				if (transaction.State == "committing")
				{
					DailyLimits.Send(this, transaction, "commit");
				}
				else if (transaction.State == "reserving")
				{
					DailyLimits.Send(this, transaction, "reserve");
				}
				Reply(sender, "result", message.Id, transaction);
			}
		}

		private void Publish(Transaction tx)
		{
			if (!(Notices != tx.Before))
			{
				view.GetZDO().Set("Wanted.notices", tx.After);
				Compatibility.Redraw(((Component)this).gameObject);
			}
		}

		internal void QuotaReply(QuotaWire wire)
		{
			if (!IsAvailable || !view.IsOwner())
			{
				return;
			}
			BoardState state = State();
			Transaction transaction = Find(state, wire.Id);
			if (transaction == null || transaction.PlayerId != wire.Player || !transaction.NeedsDailyQuota)
			{
				return;
			}
			if (wire.Action == "retry")
			{
				if (transaction.State == "committing" && quotaWarning != transaction.Id)
				{
					quotaWarning = transaction.Id;
					Reply(transaction.PlayerPeer, "warning", transaction.Id, null, "Daily limit confirmation is pending. Do not repeat payment; keep your receipt.");
				}
			}
			else if (transaction.State == "cancelled")
			{
				if (wire.Action == "reserved")
				{
					DailyLimits.Send(this, transaction, "release");
					return;
				}
				transaction.QuotaSettled = true;
				Save(state);
			}
			else if (transaction.State == "reserving")
			{
				if (wire.Action == "reserved" || wire.Action == "unlimited")
				{
					if (wire.Action == "unlimited")
					{
						transaction.NeedsDailyQuota = false;
						transaction.QuotaSettled = true;
					}
					if (Plugin.Now >= transaction.Expires || Notices != transaction.Before || box.IsInUse())
					{
						transaction.State = "cancelled";
						transaction.Reason = "The board changed or the reservation expired. No payment taken.";
						transaction.CooldownUntil = 0.0;
						Save(state);
						if (transaction.NeedsDailyQuota)
						{
							DailyLimits.Send(this, transaction, "release");
						}
						Reply(transaction.PlayerPeer, "result", transaction.Id, transaction);
					}
					else
					{
						transaction.State = "prepared";
						Save(state);
						Reply(transaction.PlayerPeer, "offer", transaction.Id, transaction);
					}
				}
				else
				{
					transaction.State = "cancelled";
					transaction.QuotaSettled = true;
					transaction.CooldownUntil = 0.0;
					transaction.Reason = ((wire.Message.Length > 0) ? wire.Message : "Daily allowance could not be reserved. No payment taken.");
					Save(state);
					Reply(transaction.PlayerPeer, "result", transaction.Id, transaction);
				}
			}
			else if (transaction.State == "committing")
			{
				if (wire.Action == "committed")
				{
					transaction.State = "committed";
					transaction.QuotaSettled = true;
					Save(state);
					Publish(transaction);
					Reply(transaction.PlayerPeer, "result", transaction.Id, transaction);
				}
				else if (wire.Action == "denied" || wire.Action == "cancelled")
				{
					transaction.State = "cancelled";
					transaction.QuotaSettled = true;
					transaction.Reason = wire.Message;
					Save(state);
					Reply(transaction.PlayerPeer, "result", transaction.Id, transaction);
				}
			}
		}
	}
	internal static class Compatibility
	{
		internal const string WantedGuid = "nick.valheim.wanted";

		internal const string PrefabName = "nick_wanted_board";

		internal const string NoticeKey = "Wanted.notices";

		internal static Type BoardType;

		internal static Type FaceType;

		internal static Type PrefabType;

		internal static MethodInfo Make;

		internal static MethodInfo Write;

		internal static MethodInfo Read;

		internal static MethodInfo Show;

		internal static FieldInfo Maximum;

		internal static bool Ready;

		internal static void Check()
		{
			PluginInfo val = Chainloader.PluginInfos["nick.valheim.wanted"];
			if (val.Metadata.Version != new Version(1, 0, 2))
			{
				throw new NotSupportedException("This preview targets Wanted 1.0.2; found " + val.Metadata.Version);
			}
			Assembly asm = ((object)val.Instance).GetType().Assembly;
			BoardType = Need("NoticeBoard");
			FaceType = Need("BoardFace");
			PrefabType = Need("Board");
			Type type = Need("Contract");
			Make = AccessTools.Method(Need("Contracts"), "Make", new Type[1] { typeof(Random) }, (Type[])null) ?? throw new MissingMethodException("Contracts.Make(Random)");
			Write = AccessTools.Method(type, "Write", Type.EmptyTypes, (Type[])null) ?? throw new MissingMethodException("Contract.Write");
			Read = AccessTools.Method(type, "Read", new Type[1] { typeof(string) }, (Type[])null) ?? throw new MissingMethodException("Contract.Read");
			Show = AccessTools.Method(BoardType, "Show", new Type[1] { typeof(bool) }, (Type[])null) ?? throw new MissingMethodException("NoticeBoard.Show");
			Maximum = AccessTools.Field(((object)val.Instance).GetType(), "MaxNotices") ?? throw new MissingFieldException("Plugin.MaxNotices");
			string[] array = new string[2] { "m_width", "m_height" };
			foreach (string text in array)
			{
				if (AccessTools.Field(typeof(Inventory), text) == null)
				{
					throw new MissingFieldException("Inventory." + text);
				}
			}
			array = new string[3] { "Post", "RPC_Take", "RequestTake" };
			foreach (string text2 in array)
			{
				if (AccessTools.Method(BoardType, text2, (Type[])null, (Type[])null) == null)
				{
					throw new MissingMethodException(text2);
				}
			}
			Ready = true;
			Type Need(string name)
			{
				return asm.GetType("Wanted." + name, throwOnError: true);
			}
		}

		internal static bool IsBoard(GameObject go)
		{
			if ((Object)(object)go != (Object)null)
			{
				return ((Object)go).name.Replace("(Clone)", "") == "nick_wanted_board";
			}
			return false;
		}

		internal static string? OpenReply(Container box, ZNetView view)
		{
			IDictionary registered = AccessTools.Field(typeof(ZNetView), "m_functions")?.GetValue(view) as IDictionary;
			return ChestReply.Resolve(box, registered, (string name) => StringExtensionMethods.GetStableHashCode(name));
		}

		internal static int MaxNotices()
		{
			object value = Maximum.GetValue(null);
			return Math.Max(1, Math.Min(10, (int)value.GetType().GetProperty("Value").GetValue(value, null)));
		}

		internal static int Count(string notices)
		{
			return Rules.CountNotices(notices, (string n) => Read.Invoke(null, new object[1] { n }) != null);
		}

		internal static string Generate(int count, Random random)
		{
			if (count < 1 || count > 10)
			{
				throw new ArgumentOutOfRangeException("count");
			}
			string[] array = new string[10];
			int[] array2 = (from _ in Enumerable.Range(0, 10)
				orderby random.Next()
				select _).Take(count).ToArray();
			foreach (int num2 in array2)
			{
				object obj = Make.Invoke(null, new object[1] { random });
				if (obj == null)
				{
					throw new InvalidOperationException("Wanted could not generate enough notices; no payment taken.");
				}
				array[num2] = (string)Write.Invoke(obj, Array.Empty<object>());
			}
			return string.Join(";", array);
		}

		internal static void Redraw(GameObject go)
		{
			Component component = go.GetComponent(BoardType);
			if ((Object)(object)component != (Object)null)
			{
				Show.Invoke(component, new object[1] { true });
			}
		}
	}
	internal sealed class QuotaWire
	{
		public string Action = "";

		public string Id = "";

		public string Player = "";

		public string Message = "";

		public long World;

		public long BoardUser;

		public long PlayerUser;

		public long RequesterPeer;

		public uint BoardObject;

		public uint PlayerObject;

		public double Expires;
	}
	internal sealed class QuotaSave
	{
		public long? World;

		public DailyQuota? Ledger;
	}
	internal static class DailyLimits
	{
		private const string Ask = "friends.valheim.wantedextensions.DailyQuota.v1";

		private const string Answer = "friends.valheim.wantedextensions.DailyQuota.v1.Reply";

		private static ZRoutedRpc? registered;

		private static DailyQuota? ledger;

		private static long? loadedWorld;

		private static string? path;

		private static string? lastError;

		internal static void ResetSession()
		{
			ledger = null;
			loadedWorld = null;
			path = null;
			lastError = null;
		}

		internal static void Update()
		{
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance != null && !((Object)(object)ZNet.instance == (Object)null) && registered != instance)
			{
				instance.Register<string>("friends.valheim.wantedextensions.DailyQuota.v1", (Action<long, string>)OnAsk);
				instance.Register<string>("friends.valheim.wantedextensions.DailyQuota.v1.Reply", (Action<long, string>)OnAnswer);
				registered = instance;
			}
		}

		internal static void Send(BoardAgent board, Transaction tx, string action)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ZNet instance = ZNet.instance;
				if ((Object)(object)instance == (Object)null || ZRoutedRpc.instance == null)
				{
					return;
				}
				QuotaWire obj = new QuotaWire
				{
					Action = action,
					Id = tx.Id,
					Player = tx.PlayerId,
					World = instance.GetWorldUID()
				};
				ZDOID id = board.Id;
				obj.BoardUser = ((ZDOID)(ref id)).UserID;
				id = board.Id;
				obj.BoardObject = ((ZDOID)(ref id)).ID;
				obj.PlayerUser = tx.PlayerObjectUser;
				obj.PlayerObject = tx.PlayerObjectId;
				obj.RequesterPeer = tx.PlayerPeer;
				obj.Expires = tx.Expires;
				QuotaWire quotaWire = obj;
				if (instance.IsServer())
				{
					Handle(board.Owner, quotaWire, board.QuotaReply);
					return;
				}
				long? num = ServerConnection.CurrentPeerId(instance);
				if (num.HasValue)
				{
					ZRoutedRpc.instance.InvokeRoutedRPC(num.Value, "friends.valheim.wantedextensions.DailyQuota.v1", new object[1] { Json.Write(quotaWire) });
				}
			}
			catch (Exception e)
			{
				Warn(e);
			}
		}

		private static void OnAsk(long sender, string text)
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || text.Length > 16384)
			{
				return;
			}
			try
			{
				QuotaWire quotaWire = Json.Read<QuotaWire>(text);
				if (quotaWire != null)
				{
					Handle(sender, quotaWire, delegate(QuotaWire reply)
					{
						ZRoutedRpc.instance.InvokeRoutedRPC(sender, "friends.valheim.wantedextensions.DailyQuota.v1.Reply", new object[1] { Json.Write(reply) });
					});
				}
			}
			catch (Exception e)
			{
				Warn(e);
			}
		}

		private static void OnAnswer(long sender, string text)
		{
			if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || text.Length > 16384)
			{
				return;
			}
			try
			{
				if (!ServerConnection.IsCurrentServer(ZNet.instance, sender))
				{
					return;
				}
				QuotaWire wire = Json.Read<QuotaWire>(text);
				if (wire == null || wire.World != ZNet.instance.GetWorldUID())
				{
					return;
				}
				Plugin.Boards.FirstOrDefault(delegate(BoardAgent b)
				{
					//IL_0012: Unknown result type (might be due to invalid IL or missing references)
					//IL_0017: Unknown result type (might be due to invalid IL or missing references)
					//IL_002d: 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)
					if ((Object)(object)b != (Object)null && b.IsAvailable)
					{
						ZDOID id = b.Id;
						if (((ZDOID)(ref id)).UserID == wire.BoardUser)
						{
							id = b.Id;
							return ((ZDOID)(ref id)).ID == wire.BoardObject;
						}
					}
					return false;
				})?.QuotaReply(wire);
			}
			catch (Exception e)
			{
				Warn(e);
			}
		}

		private static void Handle(long sender, QuotaWire wire, Action<QuotaWire> reply)
		{
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || ZDOMan.instance == null || wire.World != ZNet.instance.GetWorldUID() || !Guid.TryParseExact(wire.Id, "N", out var _) || wire.Player == null || wire.Player.Length > 30 || (wire.Action != "reserve" && wire.Action != "commit" && wire.Action != "release"))
			{
				return;
			}
			ZDO zDO = ZDOMan.instance.GetZDO(new ZDOID(wire.BoardUser, wire.BoardObject));
			if (zDO == null || zDO.GetOwner() != sender)
			{
				return;
			}
			string action = wire.Action;
			try
			{
				RerollSettings effective = Plugin.Effective;
				if (effective == null)
				{
					Respond("retry", "Waiting for valid server settings.");
					return;
				}
				if (action == "reserve")
				{
					if (!DailyQuota.Enabled(effective))
					{
						Respond("unlimited");
						return;
					}
					ZDO zDO2 = ZDOMan.instance.GetZDO(new ZDOID(wire.PlayerUser, wire.PlayerObject));
					if (zDO2 == null || zDO2.GetOwner() != wire.RequesterPeer || zDO2.GetLong("playerID", 0L).ToString(CultureInfo.InvariantCulture) != wire.Player || Vector3.Distance(zDO2.GetPosition(), zDO.GetPosition()) > 6f)
					{
						Respond("denied", "Player identity or distance changed. No payment taken.");
						return;
					}
				}
				if ((Object)(object)EnvMan.instance == (Object)null)
				{
					Respond("retry", "Waiting for the world's day clock.");
					return;
				}
				Load(wire.World);
				DailyQuota dailyQuota = ledger.Copy();
				string board = wire.BoardUser.ToString(CultureInfo.InvariantCulture) + ":" + wire.BoardObject.ToString(CultureInfo.InvariantCulture);
				QuotaResult quotaResult = dailyQuota.Apply(action, wire.Id, board, wire.Player, EnvMan.instance.GetDay(), Plugin.Now, wire.Expires, effective);
				if (quotaResult.Changed)
				{
					Save(wire.World, dailyQuota);
				}
				lastError = null;
				Respond(quotaResult.State, quotaResult.Message);
			}
			catch (Exception e)
			{
				Warn(e);
				Respond("retry", "Server daily-limit storage is unavailable. Request retained; check the server log.");
			}
			void Respond(string state, string message = "")
			{
				wire.Action = state;
				wire.Message = message;
				reply(wire);
			}
		}

		private static void Load(long world)
		{
			if (loadedWorld == world && ledger != null)
			{
				return;
			}
			path = Path.Combine(Paths.ConfigPath, "friends.valheim.wantedextensions.limits." + world.ToString(CultureInfo.InvariantCulture) + ".json");
			DailyQuota dailyQuota;
			if (File.Exists(path))
			{
				if (new FileInfo(path).Length > 8388608)
				{
					throw new IOException("Daily quota ledger exceeds 8 MiB.");
				}
				QuotaSave quotaSave = Json.Read<QuotaSave>(File.ReadAllText(path));
				if (quotaSave == null || quotaSave.World != world || quotaSave.Ledger == null)
				{
					throw new IOException("Invalid world quota ledger; preserve it for recovery.");
				}
				dailyQuota = quotaSave.Ledger;
				dailyQuota.Validate();
			}
			else
			{
				if (File.Exists(path + ".bak") || File.Exists(path + ".tmp"))
				{
					throw new IOException("Daily quota ledger is missing but recovery files exist. Preserve them for admin recovery.");
				}
				dailyQuota = new DailyQuota();
			}
			ledger = dailyQuota;
			loadedWorld = world;
		}

		private static void Save(long world, DailyQuota next)
		{
			next.Validate();
			string text = Json.Write(new QuotaSave
			{
				World = world,
				Ledger = next
			}, pretty: true);
			if (text.Length > 8388608)
			{
				throw new IOException("Daily quota ledger exceeds 8 MiB.");
			}
			Directory.CreateDirectory(Paths.ConfigPath);
			string sourceFileName = path + ".tmp";
			File.WriteAllText(sourceFileName, text);
			if (File.Exists(path))
			{
				File.Replace(sourceFileName, path, path + ".bak");
			}
			else
			{
				File.Move(sourceFileName, path);
			}
			ledger = next;
		}

		private static void Warn(Exception e)
		{
			string text = e.GetType().FullName + ": " + e.Message;
			if (!(lastError == text))
			{
				lastError = text;
				Plugin.Warn("Daily reroll limits unavailable; pending requests are retained. " + e);
			}
		}
	}
	internal static class InventoryApi
	{
		private static OptionalMethod remove = null;

		private static OptionalMethod add = null;

		private static OptionalMethod canAdd = null;

		private static OptionalMethod clone = null;

		internal static string? Problem { get; private set; } = "Payment API has not been checked.";

		internal static void Check()
		{
			try
			{
				Type typeFromHandle = typeof(Inventory);
				Type typeFromHandle2 = typeof(ItemData);
				remove = OptionalMethod.Bind(typeFromHandle, "RemoveItem", typeof(bool), typeFromHandle2, typeof(int));
				add = OptionalMethod.Bind(typeFromHandle, "AddItem", typeof(bool), typeFromHandle2);
				canAdd = OptionalMethod.Bind(typeFromHandle, "CanAddItem", typeof(bool), typeFromHandle2, typeof(int));
				clone = OptionalMethod.Bind(typeFromHandle2, "Clone", typeFromHandle2);
				Problem = null;
			}
			catch (Exception ex)
			{
				Problem = "Payment/refund API is unsupported: " + ex.Message;
			}
		}

		internal static bool Remove(Inventory inv, ItemData item, int count)
		{
			return (bool)remove.Invoke(inv, item, count);
		}

		internal static bool Add(Inventory inv, ItemData item)
		{
			return (bool)add.Invoke(inv, item);
		}

		internal static bool CanAdd(Inventory inv, ItemData item, int count)
		{
			return (bool)canAdd.Invoke(inv, item, count);
		}

		internal static ItemData Clone(ItemData item)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return (ItemData)clone.Invoke(item);
		}
	}
	internal static class Json
	{
		private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
		{
			TypeNameHandling = (TypeNameHandling)0,
			MaxDepth = 32
		};

		internal static string Write(object value, bool pretty = false)
		{
			return JsonConvert.SerializeObject(value, (Formatting)(pretty ? 1 : 0), Settings);
		}

		internal static T? Read<T>(string text)
		{
			return JsonConvert.DeserializeObject<T>(text, Settings);
		}
	}
	internal static class Patches
	{
		internal static void BeforeContainer(Container __instance)
		{
			if (Compatibility.IsBoard(((Component)__instance).gameObject))
			{
				RerollSettings effective = Plugin.Effective;
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				ZDO val = ((component != null) ? component.GetZDO() : null);
				__instance.m_width = Math.Max(effective?.Columns ?? 5, (val != null) ? val.GetInt("WantedExtensions.width", 5) : 5);
				__instance.m_height = Math.Max(effective?.Rows ?? 2, (val != null) ? val.GetInt("WantedExtensions.height", 2) : 2);
			}
		}

		internal static void AfterContainer(Container __instance)
		{
			if (Compatibility.IsBoard(((Component)__instance).gameObject) && (Object)(object)((Component)__instance).GetComponent<BoardAgent>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<BoardAgent>();
			}
		}

		internal static void AfterRegister()
		{
			object? obj = AccessTools.Field(Compatibility.PrefabType, "Prefab")?.GetValue(null);
			GameObject val = (GameObject)((obj is GameObject) ? obj : null);
			if ((Object)(object)val != (Object)null && Plugin.Effective != null)
			{
				Container component = val.GetComponent<Container>();
				if ((Object)(object)component != (Object)null)
				{
					component.m_width = Plugin.Effective.Columns;
					component.m_height = Plugin.Effective.Rows;
				}
			}
			if ((Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			Container[] array = Object.FindObjectsOfType<Container>();
			foreach (Container val2 in array)
			{
				if (Compatibility.IsBoard(((Component)val2).gameObject) && (Object)(object)((Component)val2).GetComponent<BoardAgent>() == (Object)null)
				{
					((Component)val2).gameObject.AddComponent<BoardAgent>();
				}
			}
		}

		internal static bool FaceInteract(Component __instance, Humanoid user, bool hold, bool alt, ref bool __result)
		{
			if (!alt || hold || (Object)(object)user != (Object)(object)Player.m_localPlayer)
			{
				return true;
			}
			BoardAgent componentInParent = __instance.GetComponentInParent<BoardAgent>();
			if ((Object)(object)componentInParent == (Object)null)
			{
				return true;
			}
			componentInParent.Request();
			__result = true;
			return false;
		}

		internal static void Hover(Component __instance, ref string __result)
		{
			if ((Object)(object)__instance.GetComponentInParent<BoardAgent>() == (Object)null)
			{
				return;
			}
			RerollSettings effective = Plugin.Effective;
			if (effective == null)
			{
				__result += "\nWanted Extensions: waiting for server settings.";
			}
			else
			{
				if (!effective.Enabled)
				{
					return;
				}
				if (!__instance.GetComponentInParent<BoardAgent>().CanPurchase(out string problem))
				{
					__result = __result + "\nReroll unavailable: " + problem;
					return;
				}
				__result += $"\n[Shift + Use] Reroll notices ({effective.CostAmount} {effective.CostItem})";
				if (effective.BoardDailyLimitEnabled)
				{
					__result += $"\nBoard limit: {effective.BoardDailyLimit} successful rerolls per day.";
				}
				if (effective.PlayerDailyLimitEnabled)
				{
					__result += $"\nYour limit: {effective.PlayerDailyLimit} per day across all boards.";
				}
			}
		}

		internal static bool ContainerInteract(Container __instance, ref bool __result)
		{
			BoardAgent component = ((Component)__instance).GetComponent<BoardAgent>();
			if ((Object)(object)component == (Object)null || !component.Busy)
			{
				return true;
			}
			Plugin.Tell("Someone is rerolling this board. Please wait.");
			__result = false;
			return false;
		}

		internal static bool Take(Component __instance)
		{
			BoardAgent component = __instance.GetComponent<BoardAgent>();
			if (component == null || !component.Busy)
			{
				return true;
			}
			Plugin.Tell("Someone is rerolling this board. Please wait.");
			return false;
		}

		internal static bool OpenOnOwner(Container __instance, long __0)
		{
			BoardAgent component = ((Component)__instance).GetComponent<BoardAgent>();
			ZNetView component2 = ((Component)__instance).GetComponent<ZNetView>();
			if (component == null || !component.Busy || (Object)(object)component2 == (Object)null || !component2.IsOwner())
			{
				return true;
			}
			if (!component.TryOpenReply(out string reply))
			{
				return true;
			}
			component2.InvokeRPC(__0, reply, new object[1] { false });
			component.WarnPeer(__0);
			return false;
		}

		internal static bool TakeOnOwner(Component __instance, long sender, int slot)
		{
			BoardAgent component = __instance.GetComponent<BoardAgent>();
			if (component == null || !component.Busy)
			{
				return true;
			}
			ZNetView component2 = __instance.GetComponent<ZNetView>();
			if (component2.IsOwner())
			{
				component2.InvokeRPC(sender, "Wanted_Taken", new object[2] { slot, "" });
				component.WarnPeer(sender);
			}
			return false;
		}

		internal static bool Post(Component __instance)
		{
			BoardAgent component = __instance.GetComponent<BoardAgent>();
			if (component == null)
			{
				return true;
			}
			return !component.Busy;
		}
	}
	internal sealed class RefundItem
	{
		public string Prefab = "";

		public int Amount;

		public int Quality;

		public int Variant;

		public int WorldLevel;

		public float Durability;

		public long CrafterId;

		public string CrafterName = "";

		public Dictionary<string, string> Custom = new Dictionary<string, string>();

		internal static RefundItem Capture(ItemData item, int amount)
		{
			return new RefundItem
			{
				Prefab = Payments.Prefab(item),
				Amount = amount,
				Quality = item.m_quality,
				Variant = item.m_variant,
				WorldLevel = item.m_worldLevel,
				Durability = item.m_durability,
				CrafterId = item.m_crafterID,
				CrafterName = item.m_crafterName,
				Custom = new Dictionary<string, string>(item.m_customData)
			};
		}

		internal ItemData Restore(int amount)
		{
			GameObject prefab = ZNetScene.instance.GetPrefab(Prefab);
			if ((Object)(object)prefab == (Object)null || (Object)(object)prefab.GetComponent<ItemDrop>() == (Object)null)
			{
				throw new InvalidOperationException("Refund item unavailable: " + Prefab);
			}
			ItemData obj = InventoryApi.Clone(prefab.GetComponent<ItemDrop>().m_itemData);
			obj.m_dropPrefab = prefab;
			obj.m_stack = amount;
			obj.m_quality = Quality;
			obj.m_variant = Variant;
			obj.m_worldLevel = WorldLevel;
			obj.m_durability = Durability;
			obj.m_crafterID = CrafterId;
			obj.m_crafterName = CrafterName;
			obj.m_customData = new Dictionary<string, string>(Custom);
			return obj;
		}
	}
	internal sealed class Receipt
	{
		public string Id = "";

		public long World;

		public string Character = "";

		public long BoardUser;

		public uint BoardObject;

		public string CostItem = "";

		public int CostAmount;

		public string State = "requested";

		public List<RefundItem> Items = new List<RefundItem>();
	}
	internal static class Payments
	{
		private static readonly string FileName = Path.Combine(Paths.ConfigPath, "friends.valheim.wantedextensions.receipts.json");

		private static List<Receipt> receipts = new List<Receipt>();

		private static readonly HashSet<string> announced = new HashSet<string>();

		internal static void ResetSession()
		{
			announced.Clear();
		}

		internal static void Load()
		{
			if (File.Exists(FileName))
			{
				receipts = Json.Read<List<Receipt>>(File.ReadAllText(FileName)) ?? throw new IOException("Invalid receipts journal; preserve it for recovery.");
			}
		}

		private static void Save()
		{
			Directory.CreateDirectory(Paths.ConfigPath);
			string text = FileName + ".tmp";
			File.WriteAllText(text, Json.Write(receipts, pretty: true));
			if (File.Exists(FileName))
			{
				File.Replace(text, FileName, FileName + ".bak");
			}
			else
			{
				File.Move(text, FileName);
			}
		}

		private static bool ThisPlayer(Receipt r)
		{
			if ((Object)(object)Player.m_localPlayer != (Object)null && (Object)(object)ZNet.instance != (Object)null && r.World == ZNet.instance.GetWorldUID())
			{
				return r.Character == Player.m_localPlayer.GetPlayerID().ToString(CultureInfo.InvariantCulture);
			}
			return false;
		}

		private static bool Outstanding(Receipt r)
		{
			if (r.State != "committed" && r.State != "refunded")
			{
				return r.State != "rejected";
			}
			return false;
		}

		internal static bool PendingFor(ZDOID board)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return receipts.Any((Receipt r) => ThisPlayer(r) && r.BoardUser == ((ZDOID)(ref board)).UserID && r.BoardObject == ((ZDOID)(ref board)).ID && Outstanding(r));
		}

		internal static string Prefab(ItemData item)
		{
			if (!((Object)(object)item.m_dropPrefab != (Object)null))
			{
				return "";
			}
			return ((Object)item.m_dropPrefab).name;
		}

		internal static Wire Message(Receipt r, string action)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			ZDOID zDOID = ((Character)Player.m_localPlayer).GetZDOID();
			return new Wire
			{
				Action = action,
				Id = r.Id,
				Character = r.Character,
				World = r.World,
				PlayerUser = ((ZDOID)(ref zDOID)).UserID,
				PlayerObject = ((ZDOID)(ref zDOID)).ID
			};
		}

		internal static void Begin(BoardAgent board, RerollSettings settings)
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			if (!board.CanPurchase(out string problem))
			{
				Plugin.Tell(problem + " No payment taken.");
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead())
			{
				return;
			}
			if ((from i in ((Humanoid)localPlayer).GetInventory().GetAllItems()
				where Prefab(i) == settings.CostItem && !i.m_equipped
				select i).Sum((ItemData i) => i.m_stack) < settings.CostAmount)
			{
				Plugin.Tell($"Need {settings.CostAmount} {settings.CostItem} in your inventory (equipped items excluded).");
				return;
			}
			Receipt obj = new Receipt
			{
				Id = Guid.NewGuid().ToString("N"),
				World = ZNet.instance.GetWorldUID(),
				Character = localPlayer.GetPlayerID().ToString(CultureInfo.InvariantCulture)
			};
			ZDOID id = board.Id;
			obj.BoardUser = ((ZDOID)(ref id)).UserID;
			id = board.Id;
			obj.BoardObject = ((ZDOID)(ref id)).ID;
			obj.CostItem = settings.CostItem;
			obj.CostAmount = settings.CostAmount;
			Receipt receipt = obj;
			receipts.Add(receipt);
			try
			{
				Save();
				board.SendToOwner(Message(receipt, "request"));
				Plugin.Tell("Reroll requested. Please wait.");
			}
			catch (Exception e)
			{
				receipt.State = "rejected";
				Plugin.Error(e);
				Plugin.Tell("Could not start reroll; no payment taken.");
			}
		}

		internal static void OnReply(BoardAgent board, Wire wire)
		{
			Receipt receipt = receipts.FirstOrDefault(delegate(Receipt r)
			{
				//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_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)
				if (r.Id == wire.Id && ThisPlayer(r))
				{
					long boardUser = r.BoardUser;
					ZDOID id = board.Id;
					if (boardUser == ((ZDOID)(ref id)).UserID)
					{
						uint boardObject = r.BoardObject;
						id = board.Id;
						return boardObject == ((ZDOID)(ref id)).ID;
					}
				}
				return false;
			});
			if (receipt == null || !Outstanding(receipt))
			{
				return;
			}
			if (wire.Action == "rejected" && receipt.State == "requested")
			{
				receipt.State = "rejected";
				Save();
				Plugin.Tell(wire.Message);
				return;
			}
			Transaction transaction = wire.Transaction;
			if (transaction == null)
			{
				if (receipt.State == "requested")
				{
					receipt.State = "rejected";
					Save();
					Plugin.Tell("Reroll request was not recorded. No payment taken; try again.");
				}
				else
				{
					Announce(receipt, "Reroll outcome unavailable. Receipt retained; do not retry payment or refund until an admin checks it.");
				}
			}
			else
			{
				if (transaction.Id != receipt.Id || transaction.PlayerId != receipt.Character || transaction.CostItem != receipt.CostItem || transaction.CostAmount != receipt.CostAmount)
				{
					return;
				}
				if (transaction.State == "prepared")
				{
					if (receipt.State == "requested")
					{
						Charge(board, receipt);
					}
					else if (receipt.State == "charged")
					{
						board.SendToOwner(Message(receipt, "paid"));
					}
				}
				else if (transaction.State == "committed")
				{
					if (receipt.State != "charged")
					{
						Announce(receipt, "Reroll outcome needs manual review; receipt retained.");
						return;
					}
					receipt.State = "committed";
					Save();
					Plugin.Tell($"Board rerolled: {transaction.BeforeCount} → {transaction.AfterCount} notices. Paid {transaction.CostAmount} {transaction.CostItem}.");
				}
				else if (transaction.State == "cancelled")
				{
					if (receipt.State == "requested")
					{
						receipt.State = "rejected";
						Save();
						Plugin.Tell(transaction.Reason);
					}
					else if (receipt.State == "charged" || receipt.State == "refunding")
					{
						receipt.State = "refunding";
						Save();
						Refund(receipt);
					}
					else
					{
						Announce(receipt, "Payment was interrupted during inventory mutation. Receipt retained for manual reconciliation; no automatic refund.");
					}
				}
			}
		}

		private static void Charge(BoardAgent board, Receipt receipt)
		{
			if (!board.CanPurchase(out string problem))
			{
				board.SendToOwner(Message(receipt, "declined"));
				Plugin.Tell(problem + " No payment taken.");
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead())
			{
				board.SendToOwner(Message(receipt, "declined"));
				return;
			}
			List<ItemData> list = (from i in ((Humanoid)localPlayer).GetInventory().GetAllItems()
				where Prefab(i) == receipt.CostItem && !i.m_equipped
				select i).ToList();
			if (list.Sum((ItemData i) => i.m_stack) < receipt.CostAmount)
			{
				board.SendToOwner(Message(receipt, "declined"));
				return;
			}
			int num = receipt.CostAmount;
			List<(ItemData, int)> list2 = new List<(ItemData, int)>();
			foreach (ItemData item in list)
			{
				int num2 = Math.Min(num, item.m_stack);
				if (num2 == 0)
				{
					break;
				}
				list2.Add((item, num2));
				receipt.Items.Add(RefundItem.Capture(item, num2));
				num -= num2;
			}
			receipt.State = "charging";
			Save();
			try
			{
				foreach (var item2 in list2)
				{
					if (!InventoryApi.Remove(((Humanoid)localPlayer).GetInventory(), item2.Item1, item2.Item2))
					{
						throw new InvalidOperationException("Inventory changed during payment.");
					}
				}
				receipt.State = "charged";
				Save();
				board.SendToOwner(Message(receipt, "paid"));
			}
			catch (Exception e)
			{
				Plugin.Error(e);
				Announce(receipt, "Payment needs manual review. No further charge will be attempted; keep your receipts journal.");
			}
		}

		private static void Refund(Receipt receipt)
		{
			if (InventoryApi.Problem != null)
			{
				Announce(receipt, InventoryApi.Problem + " Refund receipt retained.");
				return;
			}
			Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory();
			foreach (RefundItem item in receipt.Items)
			{
				while (item.Amount > 0)
				{
					ItemData val = item.Restore(item.Amount);
					int num = (val.m_stack = Math.Min(item.Amount, Math.Max(1, val.m_shared.m_maxStackSize)));
					if (!InventoryApi.CanAdd(inventory, val, num))
					{
						Announce(receipt, "Reroll cancelled. Make room in your inventory for the pending refund; it will retry automatically.");
						return;
					}
					receipt.State = "refund-writing";
					Save();
					if (!InventoryApi.Add(inventory, val))
					{
						Announce(receipt, "Refund insertion needs manual review; receipt retained.");
						return;
					}
					item.Amount -= num;
					receipt.State = "refunding";
					Save();
				}
			}
			receipt.State = "refunded";
			Save();
			Plugin.Tell("Reroll cancelled. Your payment was returned.");
		}

		private static void Announce(Receipt r, string text)
		{
			if (announced.Add(r.Id + ":" + r.State))
			{
				Plugin.Tell(text + " Transaction: " + r.Id);
			}
		}

		internal static void Retry()
		{
			if (InventoryApi.Problem != null || (Object)(object)Player.m_localPlayer == (Object)null || ((Character)Player.m_localPlayer).IsDead() || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			Receipt[] array = receipts.Where((Receipt r2) => ThisPlayer(r2) && Outstanding(r2)).ToArray();
			foreach (Receipt r in array)
			{
				if (r.State == "charging" || r.State == "refund-writing")
				{
					Announce(r, "Interrupted inventory operation; automatic replay disabled. Ask an admin to reconcile the receipt and inventory.");
					continue;
				}
				BoardAgent boardAgent = Plugin.Boards.FirstOrDefault(delegate(BoardAgent b)
				{
					//IL_0012: Unknown result type (might be due to invalid IL or missing references)
					//IL_0017: Unknown result type (might be due to invalid IL or missing references)
					//IL_002d: 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)
					if ((Object)(object)b != (Object)null && b.IsAvailable)
					{
						ZDOID id = b.Id;
						if (((ZDOID)(ref id)).UserID == r.BoardUser)
						{
							id = b.Id;
							return ((ZDOID)(ref id)).ID == r.BoardObject;
						}
					}
					return false;
				});
				if (!((Object)(object)boardAgent == (Object)null))
				{
					if (r.State == "refunding")
					{
						Refund(r);
					}
					else
					{
						boardAgent.SendToOwner(Message(r, (r.State == "charged") ? "paid" : "query"));
					}
				}
			}
		}
	}
	[BepInPlugin("friends.valheim.wantedextensions", "Wanted Extensions", "0.1.9")]
	[BepInDependency("nick.valheim.wanted", "1.0.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Guid = "friends.valheim.wantedextensions";

		public const string PluginVersion = "0.1.9";

		internal static Plugin Instance = null;

		internal static RerollSettings? Effective;

		internal static readonly HashSet<BoardAgent> Boards = new HashSet<BoardAgent>();

		private readonly List<ConfigEntry<int>> ints = new List<ConfigEntry<int>>();

		private ConfigEntry<string> costItem;

		private ConfigEntry<bool> rerollEnabled;

		private ConfigEntry<bool> boardLimitEnabled;

		private ConfigEntry<bool> playerLimitEnabled;

		private ConfigEntry<float> cooldown;

		private Harmony? harmony;

		private ZRoutedRpc? registered;

		private ZNet? session;

		private float nextSync;

		private float nextConfigPoll;

		private readonly LiveConfig liveConfig = new LiveConfig();

		private string? lastConfigReadError;

		private static bool notificationWarningLogged;

		private string? lastSettingsProblem;

		private long? configServerPeer;

		private const string Ask = "friends.valheim.wantedextensions.AskConfig";

		private const string Send = "friends.valheim.wantedextensions.Config";

		internal static double Now => (double)ZNet.instance.GetTime().Ticks / 10000000.0;

		private void Awake()
		{
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Expected O, but got Unknown
			Instance = this;
			bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			try
			{
				ints.Add(((BaseUnityPlugin)this).Config.Bind<int>("Chest", "Columns", 5, "Server setting: 1–8 columns."));
				ints.Add(((BaseUnityPlugin)this).Config.Bind<int>("Chest", "Rows", 8, "Server setting: 1–12 rows. Occupied cells prevent unsafe shrinking."));
				rerollEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Reroll", "Enabled", true, "Allow paid rerolls using Shift+Use on the board's wood.");
				costItem = ((BaseUnityPlugin)this).Config.Bind<string>("Reroll", "CostItem", "Coins", "Exact inventory-item prefab name, not a creature/building or translated label.");
				ints.Add(((BaseUnityPlugin)this).Config.Bind<int>("Reroll", "CostAmount", 100, "Items consumed for a successful reroll: 1–100000."));
				ints.Add(((BaseUnityPlugin)this).Config.Bind<int>("Reroll", "SameChance", 70, "Percent; three chances must total 100."));
				ints.Add(((BaseUnityPlugin)this).Config.Bind<int>("Reroll", "MinusChance", 15, "Percent chance of one fewer notice, minimum one."));
				ints.Add(((BaseUnityPlugin)this).Config.Bind<int>("Reroll", "PlusChance", 15, "Percent chance of one extra notice, capped at Wanted's maximum."));
				cooldown = ((BaseUnityPlugin)this).Config.Bind<float>("Reroll", "CooldownSeconds", 2f, "Minimum per-board lock in seconds, range 2–60; pending transactions stay locked longer.");
				boardLimitEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("DailyLimits", "BoardEnabled", false, "Limit successful paid rerolls per board per in-game day. Resets at dawn; off by default.");
				ints.Add(((BaseUnityPlugin)this).Config.Bind<int>("DailyLimits", "BoardLimit", 5, "Successful rerolls per board per in-game day when BoardEnabled is true: 1–1000."));
				playerLimitEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("DailyLimits", "PlayerEnabled", false, "Limit successful paid rerolls per character across all boards in this world. Resets at dawn; off by default.");
				ints.Add(((BaseUnityPlugin)this).Config.Bind<int>("DailyLimits", "PlayerLimit", 3, "Successful rerolls per character per in-game day when PlayerEnabled is true: 1–1000."));
			}
			finally
			{
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
			}
			InitialiseSettings();
			try
			{
				Compatibility.Check();
				InventoryApi.Check();
				if (InventoryApi.Problem != null)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)(InventoryApi.Problem + " New payments are disabled; receipt journals are retained."));
				}
				Payments.Load();
				harmony = new Harmony("friends.valheim.wantedextensions");
				Patch(typeof(Container), "Awake", "BeforeContainer", prefix: true);
				Patch(typeof(Container), "Awake", "AfterContainer", prefix: false);
				Patch(typeof(Container), "Interact", "ContainerInteract", prefix: true);
				Patch(typeof(Container), "RPC_RequestOpen", "OpenOnOwner", prefix: true, 800);
				Patch(Compatibility.PrefabType, "Register", "AfterRegister", prefix: false);
				Patch(Compatibility.FaceType, "Interact", "FaceInteract", prefix: true);
				Patch(Compatibility.FaceType, "GetHoverText", "Hover", prefix: false);
				Patch(Compatibility.BoardType, "RequestTake", "Take", prefix: true);
				Patch(Compatibility.BoardType, "RPC_Take", "TakeOnOwner", prefix: true);
				Patch(Compatibility.BoardType, "Post", "Post", prefix: true);
				RewardDelivery.Apply(harmony, delegate(string text)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)text);
				});
				PreviewCompatibility.Apply(harmony, delegate(string text)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)text);
				});
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Wanted Extensions 0.1.9 preview loaded for Wanted 1.0.2. Multiplayer acceptance tests are required before live use.");
			}
			catch (Exception ex)
			{
				Compatibility.Ready = false;
				Harmony? obj = harmony;
				if (obj != null)
				{
					obj.UnpatchSelf();
				}
				((BaseUnityPlugin)this).Logger.LogError((object)("Extension disabled: " + ex));
			}
		}

		private void Patch(Type type, string method, string patch, bool prefix, int priority = 400)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(type, method, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.FullName, method);
			HarmonyMethod val = new HarmonyMethod(typeof(Patches), patch, (Type[])null);
			val.priority = priority;
			harmony.Patch((MethodBase)methodInfo, prefix ? val : null, prefix ? null : val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private void ApplyEntries(RerollSettings s)
		{
			bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			try
			{
				ints[0].Value = s.Columns;
				ints[1].Value = s.Rows;
				rerollEnabled.Value = s.Enabled;
				costItem.Value = s.CostItem;
				ints[2].Value = s.CostAmount;
				ints[3].Value = s.Same;
				ints[4].Value = s.Minus;
				ints[5].Value = s.Plus;
				cooldown.Value = (float)s.CooldownSeconds;
				boardLimitEnabled.Value = s.BoardDailyLimitEnabled;
				ints[6].Value = s.BoardDailyLimit;
				playerLimitEnabled.Value = s.PlayerDailyLimitEnabled;
				ints[7].Value = s.PlayerDailyLimit;
			}
			finally
			{
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		private string ReadSettingsFile()
		{
			if (new FileInfo(((BaseUnityPlugin)this).Config.ConfigFilePath).Length > 65536)
			{
				throw new IOException("Config exceeds 64 KiB.");
			}
			return File.ReadAllText(((BaseUnityPlugin)this).Config.ConfigFilePath);
		}

		private void InitialiseSettings()
		{
			try
			{
				if (!File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath))
				{
					((BaseUnityPlugin)this).Config.Save();
				}
				string text = ReadSettingsFile();
				if (liveConfig.Prime(text, allowPartial: true) == ReloadResult.Rejected)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Config is invalid; new rerolls unavailable until corrected: " + liveConfig.Error));
					return;
				}
				ApplyEntries(liveConfig.LastGood);
				bool flag;
				try
				{
					SettingsFile.Parse(text);
					flag = true;
				}
				catch
				{
					flag = false;
				}
				if (!flag)
				{
					((BaseUnityPlugin)this).Config.Save();
					liveConfig.Prime(ReadSettingsFile());
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Config ready. Server file edits reload automatically; no configuration restart is required.");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Could not initialise config; file left for correction: " + ex.Message));
			}
		}

		private void PollSettings()
		{
			if (Time.unscaledTime < nextConfigPoll)
			{
				return;
			}
			nextConfigPoll = Time.unscaledTime + 1f;
			try
			{
				string text = ReadSettingsFile();
				lastConfigReadError = null;
				switch (liveConfig.Observe(text, Time.unscaledTime))
				{
				case ReloadResult.Rejected:
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Config edit rejected; last valid settings retained: " + liveConfig.Error));
					break;
				case ReloadResult.Applied:
					ApplyEntries(liveConfig.LastGood);
					Effective = liveConfig.LastGood;
					nextSync = 0f;
					((BaseUnityPlugin)this).Logger.LogInfo((object)"Server config reloaded; accepted settings will sync to clients.");
					break;
				}
			}
			catch (Exception ex)
			{
				if (!(lastConfigReadError == ex.Message))
				{
					lastConfigReadError = ex.Message;
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Cannot read config; last valid settings retained: " + ex.Message));
				}
			}
		}

		private void Update()
		{
			if (!Compatibility.Ready)
			{
				return;
			}
			if ((Object)(object)session != (Object)(object)ZNet.instance)
			{
				session = ZNet.instance;
				Effective = null;
				nextSync = 0f;
				Payments.ResetSession();
				notificationWarningLogged = false;
				lastSettingsProblem = null;
				configServerPeer = null;
				DailyLimits.ResetSession();
			}
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			if (ZNet.instance.IsServer())
			{
				PollSettings();
			}
			DailyLimits.Update();
			if (registered != rpc)
			{
				registered = rpc;
				rpc.Register("friends.valheim.wantedextensions.AskConfig", (Action<long>)OnAskConfig);
				rpc.Register<string>("friends.valheim.wantedextensions.Config", (Action<long, string>)OnConfig);
			}
			if (Time.unscaledTime < nextSync)
			{
				return;
			}
			nextSync = Time.unscaledTime + 5f;
			Maintenance.Run(delegate
			{
				if (ZNet.instance.IsServer())
				{
					Effective = liveConfig.LastGood;
				}
				else
				{
					long? num = ServerConnection.CurrentPeerId(ZNet.instance);
					if (num != configServerPeer)
					{
						Effective = null;
					}
					configServerPeer = num;
					if (!num.HasValue)
					{
						Effective = null;
					}
					else
					{
						rpc.InvokeRoutedRPC(num.Value, "friends.valheim.wantedextensions.AskConfig", Array.Empty<object>());
					}
				}
			}, ((IEnumerable<BoardAgent>)Boards.ToArray()).Select((Func<BoardAgent, Action>)((BoardAgent board) => delegate
			{
				if ((Object)(object)board != (Object)null)
				{
					board.Resize();
				}
			})), Payments.Retry, SettingsFailure, delegate(Exception e)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Chest resize failed; server settings retained: " + e));
			}, delegate(Exception e)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Payment receipt retry failed; server settings retained: " + e));
			});
		}

		private void OnAskConfig(long sender)
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			try
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(sender, "friends.valheim.wantedextensions.Config", new object[1] { Json.Write(liveConfig.LastGood) });
			}
			catch (Exception ex)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(sender, "friends.valheim.wantedextensions.Config", new object[1] { "null" });
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Invalid server configuration: " + ex.Message));
			}
		}

		private void OnConfig(long sender, string json)
		{
			if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || json.Length > 4096)
			{
				return;
			}
			try
			{
				if (!ServerConnection.IsCurrentServer(ZNet.instance, sender))
				{
					return;
				}
			}
			catch (Exception e)
			{
				SettingsFailure(e);
				return;
			}
			try
			{
				RerollSettings? obj = Json.Read<RerollSettings>(json) ?? throw new ArgumentException("Empty settings");
				obj.Validate();
				Effective = obj;
				configServerPeer = sender;
				lastSettingsProblem = null;
			}
			catch (Exception e2)
			{
				SettingsFailure(e2);
			}
		}

		private void SettingsFailure(Exception e)
		{
			Effective = null;
			string text = e.GetType().FullName + ": " + e.Message;
			if (!(lastSettingsProblem == text))
			{
				lastSettingsProblem = text;
				((BaseUnityPlugin)this).Logger.LogError((object)("Server settings sync unavailable; retrying without accepting new rerolls: " + e));
			}
		}

		private void OnDestroy()
		{
			Harmony? obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			Effective = null;
			BoardAgent[] array = Boards.ToArray();
			foreach (BoardAgent boardAgent in array)
			{
				if ((Object)(object)boardAgent != (Object)null)
				{
					Object.Destroy((Object)(object)boardAgent);
				}
			}
			Boards.Clear();
		}

		internal static void Tell(string text)
		{
			((BaseUnityPlugin)Instance).Logger.LogInfo((object)text);
			try
			{
				if (!Notification.TryShow(AccessTools.Property(typeof(MessageHud), "instance")?.GetValue(null, null) ?? AccessTools.Field(typeof(MessageHud), "instance")?.GetValue(null), "ShowMessage", (object)(MessageType)2, text, out Exception error) && !Notification.TryShow(Player.m_localPlayer, "Message", (object)(MessageType)2, text, out Exception error2) && (error != null || error2 != null))
				{
					WarnNotification(error2 ?? error);
				}
			}
			catch (Exception e)
			{
				WarnNotification(e);
			}
		}

		private static void WarnNotification(Exception e)
		{
			if (!notificationWarningLogged)
			{
				notificationWarningLogged = true;
				((BaseUnityPlugin)Instance).Logger.LogWarning((object)("On-screen notification unavailable; messages remain in this log. " + e));
			}
		}

		internal static void Error(Exception e)
		{
			((BaseUnityPlugin)Instance).Logger.LogError((object)e);
		}

		internal static void Warn(string text)
		{
			((BaseUnityPlugin)Instance).Logger.LogWarning((object)text);
		}
	}
	internal static class PreviewCompatibility
	{
		internal const string SeneaLGuid = "seneaL.valheim.ui";

		private static MethodInfo hoverObject;

		private static Type paperType;

		private static bool failed;

		internal static void Apply(Harmony harmony, Action<string> info)
		{
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Expected O, but got Unknown
			if (!Chainloader.PluginInfos.TryGetValue("seneaL.valheim.ui", out var value))
			{
				return;
			}
			try
			{
				Type type = ((object)value.Instance).GetType().Assembly.GetType("SeneaLUI.Hud.HoverView", throwOnError: true);
				MethodInfo method = type.GetMethod("Previewable", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Container) }, null);
				if (method == null || method.ReturnType != typeof(bool) || method.ContainsGenericParameters)
				{
					throw new MissingMethodException(type.FullName, "Boolean Previewable(Container)");
				}
				paperType = Compatibility.FaceType.Assembly.GetType("Wanted.NoticePaper", throwOnError: true);
				hoverObject = AccessTools.Method(typeof(Humanoid), "GetHoverObject", Type.EmptyTypes, (Type[])null);
				if (hoverObject == null || hoverObject.IsStatic || hoverObject.ReturnType != typeof(GameObject))
				{
					throw new MissingMethodException("Humanoid.GetHoverObject()");
				}
				failed = false;
				harmony.Patch((MethodBase)method, new HarmonyMethod(typeof(PreviewCompatibility), "BeforePreview", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				info("SeneaL chest preview compatibility enabled: previews use the Wanted chest, not the wood or notices.");
			}
			catch (Exception ex)
			{
				Plugin.Warn("SeneaL chest preview compatibility unavailable; keeping its original preview behaviour. " + ex);
			}
		}

		private static bool BeforePreview(Container __0, ref bool __result)
		{
			if (failed || (Object)(object)__0 == (Object)null || !Compatibility.IsBoard(((Component)__0).gameObject))
			{
				return true;
			}
			try
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer == (Object)null)
				{
					return true;
				}
				object? obj = hoverObject.Invoke(localPlayer, null);
				GameObject val = (GameObject)((obj is GameObject) ? obj : null);
				if ((Object)(object)val == (Object)null || (Object)(object)val.GetComponentInParent<Container>() != (Object)(object)__0)
				{
					return true;
				}
				Hoverable componentInParent = val.GetComponentInParent<Hoverable>();
				if (componentInParent == null || (!Compatibility.FaceType.IsInstanceOfType(componentInParent) && !paperType.IsInstanceOfType(componentInParent)))
				{
					return true;
				}
				__result = false;
				return false;
			}
			catch (Exception ex)
			{
				failed = true;
				Plugin.Warn("SeneaL chest preview compatibility stopped after an error; keeping its original preview behaviour. " + ex);
				return true;
			}
		}
	}
	internal static class RewardDelivery
	{
		internal sealed class Checkpoint
		{
			public Inventory Inventory;

			public ZDO Data;

			public byte[] Items = Array.Empty<byte>();

			public string Paid = "";

			public string Pouch = "";
		}

		private sealed class Recovery
		{
			public long World;

			public long BoardUser;

			public uint BoardObject;

			public byte[] Inventory = Array.Empty<byte>();

			public string Paid = "";

			public string Pouch = "";

			public string Error = "";
		}

		private const string PaidKey = "Wanted.paid";

		private const string PouchKey = "Wanted.pouch";

		private static bool ready;

		private static OptionalMethod add;

		private static OptionalMethod save;

		private static OptionalMethod load;

		private static OptionalMethod bytes;

		private static ConstructorInfo emptyPackage;

		private static ConstructorInfo readPackage;

		private static MethodInfo originalAdd;

		[ThreadStatic]
		private static HashSet<Inventory>? active;

		internal static void Apply(Harmony harmony, Action<string> info)
		{
			//IL_005f: 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_0081: Expected O, but got Unknown
			//IL_0081: Expected O, but got Unknown
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Expected O, but got Unknown
			MethodInfo methodInfo = null;
			bool flag = false;
			ready = false;
			try
			{
				methodInfo = AccessTools.Method(Compatibility.BoardType.Assembly.GetType("Wanted.HandIn", throwOnError: true), "Process", new Type[1] { typeof(Container) }, (Type[])null) ?? throw new MissingMethodException("Wanted.HandIn.Process(Container)");
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(RewardDelivery), "Before", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(RewardDelivery), "FinalizeHandIn", (Type[])null), (HarmonyMethod)null);
				flag = true;
				originalAdd = typeof(Inventory).GetMethod("AddItem", BindingFlags.Instance | BindingFlags.Public, null, new Type[2]
				{
					typeof(GameObject),
					typeof(int)
				}, null) ?? throw new MissingMethodException("Inventory.AddItem(GameObject, Int32)");
				if (originalAdd.ReturnType != typeof(bool))
				{
					throw new MissingMethodException("Boolean Inventory.AddItem(GameObject, Int32)");
				}
				add = OptionalMethod.Bind(typeof(Inventory), "AddItem", typeof(bool), typeof(GameObject), typeof(int));
				save = OptionalMethod.Bind(typeof(Inventory), "Save", typeof(void), typeof(ZPackage));
				load = OptionalMethod.Bind(typeof(Inventory), "Load", typeof(void), typeof(ZPackage));
				bytes = OptionalMethod.Bind(typeof(ZPackage), "GetArray", typeof(byte[]));
				emptyPackage = typeof(ZPackage).GetConstructor(Type.EmptyTypes) ?? throw new MissingMethodException("ZPackage()");
				readPackage = typeof(ZPackage).GetConstructor(new Type[1] { typeof(byte[]) }) ?? throw new MissingMethodException("ZPackage(Byte[])");
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(RewardDelivery), "SplitRewardCall", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				ready = true;
				info("Wanted reward stack protection enabled: full multi-stack amounts, verified insertion and rollback on payout failure.");
			}
			catch (Exception ex)
			{
				ready = false;
				if (flag && methodInfo != null)
				{
					try
					{
						harmony.Unpatch((MethodBase)methodInfo, AccessTools.Method(typeof(RewardDelivery), "SplitRewardCall", (Type[])null, (Type[])null));
					}
					catch (Exception e)
					{
						Plugin.Error(e);
					}
				}
				Plugin.Warn((flag ? "Wanted reward hand-ins paused; notices and materials will not be consumed. " : "Wanted reward protection could not be installed; do not claim rewards until resolved. ") + ex);
			}
		}

		private static IEnumerable<CodeInstruction> SplitRewardCall(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			CodeInstruction[] array = list.Where((CodeInstruction i) => (i.opcode == OpCodes.Call || i.opcode == OpCodes.Callvirt) && i.operand is MethodInfo methodInfo && methodInfo == originalAdd).ToArray();
			if (array.Length != 1)
			{
				throw new NotSupportedException("Expected exactly one Wanted reward AddItem call; found " + array.Length);
			}
			array[0].opcode = OpCodes.Call;
			array[0].operand = AccessTools.Method(typeof(RewardDelivery), "AddReward", (Type[])null, (Type[])null);
			return list;
		}

		private static bool Before(Container __0, out Checkpoint? __state)
		{
			__state = null;
			if (!ready)
			{
				Plugin.Tell("Wanted reward hand-in is paused for safety. Your notice and items are kept; check the BepInEx log.");
				return false;
			}
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				return false;
			}
			ZNetView component = ((Component)__0).GetComponent<ZNetView>();
			ZDO val = ((component != null) ? component.GetZDO() : null);
			Inventory inventory = __0.GetInventory();
			if (val == null || inventory == null)
			{
				return false;
			}
			HashSet<Inventory> hashSet = active ?? (active = new HashSet<Inventory>());
			if (!hashSet.Add(inventory))
			{
				return false;
			}
			try
			{
				byte[] items = Capture(inventory);
				__state = new Checkpoint
				{
					Inventory = inventory,
					Data = val,
					Items = items,
					Paid = (val.GetString("Wanted.paid", "") ?? ""),
					Pouch = (val.GetString("Wanted.pouch", "") ?? "")
				};
				return true;
			}
			catch (Exception e)
			{
				hashSet.Remove(inventory);
				ready = false;
				Plugin.Error(e);
				Plugin.Tell("Could not checkpoint Wanted's chest. Hand-in paused; no notice or materials consumed.");
				return false;
			}
		}

		private static byte[] Capture(Inventory inventory)
		{
			object obj = emptyPackage.Invoke(Array.Empty<object>());
			save.Invoke(inventory, obj);
			byte[] obj2 = (byte[])bytes.Invoke(obj);
			if (obj2.Length == 0)
			{
				throw new InvalidOperationException("Empty inventory checkpoint.");
			}
			return obj2;
		}

		private static bool AddReward(Inventory inventory, GameObject prefab, int amount)
		{
			try
			{
				GameObject obj = prefab;
				ItemDrop val = ((obj != null) ? obj.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val == (Object)null)
				{
					throw new InvalidOperationException("Reward prefab has no item data.");
				}
				RewardStacks.Deliver(amount, val.m_itemData.m_shared.m_maxStackSize, Count, (int chunk) => (bool)add.Invoke(inventory, prefab, chunk));
				return true;
			}
			catch (RewardDeliveryException)
			{
				throw;
			}
			catch (Exception inner)
			{
				throw new RewardDeliveryException("Could not deliver the complete Wanted reward.", inner);
			}
			long Count()
			{
				return (from i in inventory.GetAllItems()
					where (Object)(object)i.m_dropPrefab != (Object)null && ((Object)i.m_dropPrefab).name == ((Object)prefab).name
					select i).Sum((Func<ItemData, long>)((ItemData i) => i.m_stack));
			}
		}

		private static Exception? FinalizeHandIn(Exception? __exception, Checkpoint? __state)
		{
			if (__state == null)
			{
				return __exception;
			}
			try
			{
				if (!(__exception is RewardDeliveryException))
				{
					return __exception;
				}
				try
				{
					load.Invoke(__state.Inventory, readPackage.Invoke(new object[1] { __state.Items }));
					if (!Capture(__state.Inventory).SequenceEqual(__state.Items))
					{
						throw new InvalidOperationException("Restored inventory does not match its reward checkpoint.");
					}
					__state.Data.Set("Wanted.paid", __state.Paid);
					__state.Data.Set("Wanted.pouch", __state.Pouch);
					Plugin.Warn("Incomplete Wanted reward payout rolled back: " + __exception);
					Plugin.Tell("Wanted reward could not be fully added. Chest, notices and requirements restored; check the log before retrying.");
				}
				catch (Exception ex)
				{
					ready = false;
					Plugin.Error(ex);
					PreserveRecovery(__state, ex);
					Plugin.Tell("Wanted reward recovery needs an admin. Do not retry; keep the recovery file and check the log.");
				}
				return null;
			}
			finally
			{
				active?.Remove(__state.Inventory);
			}
		}

		private static void PreserveRecovery(Checkpoint state, Exception error)
		{
			try
			{
				Directory.CreateDirectory(Paths.ConfigPath);
				string text = Path.Combine(Paths.ConfigPath, "friends.valheim.wantedextensions.reward-recovery." + Guid.NewGuid().ToString("N") + ".json");
				Recovery recovery = new Recovery();
				ZNet instance = ZNet.instance;
				recovery.World = ((instance != null) ? instance.GetWorldUID() : 0);
				recovery.BoardUser = ((ZDOID)(ref state.Data.m_uid)).UserID;
				recovery.BoardObject = ((ZDOID)(ref state.Data.m_uid)).ID;
				recovery.Inventory = state.Items;
				recovery.Paid = state.Paid;
				recovery.Pouch = state.Pouch;
				recovery.Error = error.ToString();
				File.WriteAllText(text, Json.Write(recovery, pretty: true));
				Plugin.Warn("Saved Wanted reward recovery checkpoint: " + text);
			}
			catch (Exception e)
			{
				Plugin.Error(e);
			}
		}
	}
}
namespace WantedExtensions.Core
{
	public sealed class RerollSettings
	{
		public int Columns = 5;

		public int Rows = 8;

		public bool Enabled = true;

		public string CostItem = "Coins";

		public int CostAmount = 100;

		public int Same = 70;

		public int Minus = 15;

		public int Plus = 15;

		public double CooldownSeconds = 2.0;

		public bool BoardDailyLimitEnabled;

		public int BoardDailyLimit = 5;

		public bool PlayerDailyLimitEnabled;

		public int PlayerDailyLimit = 3;

		public void Validate()
		{
			if (Columns < 1 || Columns > 8 || Rows < 1 || Rows > 12)
			{
				throw new ArgumentException("Chest dimensions must be 1–8 columns and 1–12 rows.");
			}
			if (string.IsNullOrWhiteSpace(CostItem) || CostItem.Length > 128 || CostAmount < 1 || CostAmount > 100000)
			{
				throw new ArgumentException("Use an item prefab name and a cost between 1 and 100000.");
			}
			if (Same < 0 || Minus < 0 || Plus < 0 || (long)Same + (long)Minus + Plus != 100)
			{
				throw new ArgumentException("Reroll chances must be non-negative and total 100.");
			}
			if (double.IsNaN(CooldownSeconds) || double.IsInfinity(CooldownSeconds) || CooldownSeconds < 2.0 || CooldownSeconds > 60.0)
			{
				throw new ArgumentException("Cooldown must be 2–60 seconds.");
			}
			if (BoardDailyLimit < 1 || BoardDailyLimit > 1000 || PlayerDailyLimit < 1 || PlayerDailyLimit > 1000)
			{
				throw new ArgumentException("Daily limits must be between 1 and 1000; disable their toggles for unlimited rerolls.");
			}
		}
	}
	public static class Rules
	{
		public const int NoticeSlots = 10;

		public static int CountNotices(string? notices, Func<string, bool> isContract)
		{
			string[] array = (notices ?? "").Split(new char[1] { ';' });
			int num = 0;
			for (int i = 0; i < Math.Min(array.Length, 10); i++)
			{
				if (!string.IsNullOrEmpty(array[i]) && isContract(array[i]))
				{
					num++;
				}
			}
			return num;
		}

		public static string? RequestProblem(int current, int maximum)
		{
			if (maximum < 1 || maximum > 10)
			{
				return "The board's notice limit is invalid. Check Wanted's settings.";
			}
			if (current < 1)
			{
				return "This board is empty. Wait for dawn restocking.";
			}
			if (current > maximum)
			{
				return "The board exceeds its configured maximum. Take notices before rerolling.";
			}
			return null;
		}

		public static string? CountChangeProblem(int before, int after, int maximum)
		{
			string text = RequestProblem(before, maximum);
			if (text != null)
			{
				return text;
			}
			if (after < 1 || after > maximum || Math.Abs(after - before) > 1)
			{
				return "The reroll would exceed the allowed notice counts. Please try again.";
			}
			return null;
		}

		public static int RollCount(int current, int maximum, RerollSettings settings, int roll)
		{
			settings.Validate();
			if (RequestProblem(current, maximum) != null || roll < 0 || roll >= 100)
			{
				throw new ArgumentOutOfRangeException();
			}
			if (roll < settings.Same)
			{
				return current;
			}
			if (roll < settings.Same + settings.Minus)
			{
				if (current <= 1)
				{
					return current;
				}
				return current - 1;
			}
			if (current >= maximum)
			{
				return current;
			}
			return current + 1;
		}

		public static bool Fits(int columns, int rows, IEnumerable<(int x, int y)> positions)
		{
			foreach (var position in positions)
			{
				if (position.x < 0 || position.y < 0 || position.x >= columns || position.y >= rows)
				{
					return false;
				}
			}
			return true;
		}
	}
	public sealed class Transaction
	{
		public string Id = "";

		public long PlayerPeer;

		public string PlayerId = "";

		public string Before = "";

		public string After = "";

		public int BeforeCount;

		public int AfterCount;

		public string CostItem = "";

		public int CostAmount;

		public double Expires;

		public double CooldownUntil;

		public string State = "prepared";

		public string Reason = "";

		public bool NeedsDailyQuota;

		public bool QuotaSettled;

		public long PlayerObjectUser;

		public uint PlayerObjectId;

		public bool Busy(double now)
		{
			if (!(State == "committing") && ((!(State == "prepared") && !(State == "reserving")) || !(now < Expires)))
			{
				return now < CooldownUntil;
			}
			return true;
		}

		public string Decide(double now, string currentNotices, bool paid, bool chestInUse, int maximum = 10, Func<string, int>? countNotices = null)
		{
			if (State != "prepared")
			{
				return State;
			}
			if (!paid || now >= Expires || chestInUse || currentNotices != Before)
			{
				State = "cancelled";
				Reason = ((!paid) ? "Payment unavailable." : ((now >= Expires) ? "Reroll reservation expired." : (chestInUse ? "Someone is using this board's chest." : "The board changed; please try again.")));
				return State;
			}
			string text = Rules.CountChangeProblem(BeforeCount, AfterCount, maximum);
			if (text == null && countNotices != null && (countNotices(Before) != BeforeCount || countNotices(After) != AfterCount))
			{
				text = "The reroll's notice data does not match its count. Please try again.";
			}
			if (text != null)
			{
				State = "cancelled";
				Reason = text;
			}
			else
			{
				State = "committed";
			}
			return State;
		}
	}
	public static class Maintenance
	{
		public static void Run(Action refreshSettings, IEnumerable<Action> resizeBoards, Action retryPayments, Action<Exception> settingsError, Action<Exception> resizeError, Action<Exception> paymentError)
		{
			try
			{
				refreshSettings();
			}
			catch (Exception obj)
			{
				settingsError(obj);
			}
			foreach (Action resizeBoard in resizeBoards)
			{
				try
				{
					resizeBoard();
				}
				catch (Exception obj2)
				{
					resizeError(obj2);
				}
			}
			try
			{
				retryPayments();
			}
			catch (Exception obj3)
			{
				paymentError(obj3);
			}
		}
	}
	public static class Notification
	{
		public static bool TryShow(object? target, string methodName, object messageType, string text, out Exception? error)
		{
			error = null;
			if (target == null)
			{
				return false;
			}
			try
			{
				MethodInfo methodInfo = (from m in (from m in target.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
						where m.Name == methodName && !m.ContainsGenericParameters
						select m).Where(delegate(MethodInfo m)
					{
						ParameterInfo[] parameters2 = m.GetParameters();
						return parameters2.Length >= 2 && parameters2[0].ParameterType == messageType.GetType() && parameters2[1].ParameterType == typeof(string) && parameters2.Skip(2).All(CanSupply);
					})
					orderby m.GetParameters().Length
					select m).FirstOrDefault();
				if (methodInfo == null)
				{
					error = new MissingMethodException(target.GetType().FullName, methodName);
					return false;
				}
				ParameterInfo[] parameters = methodInfo.GetParameters();
				object[] array = new object[parameters.Length];
				array[0] = messageType;
				array[1] = text;
				for (int num = 2; num < array.Length; num++)
				{
					ParameterInfo parameterInfo = parameters[num];
					array[num] = (parameterInfo.IsOptional ? parameterInfo.DefaultValue : ((parameterInfo.ParameterType == typeof(int)) ? ((object)0) : ((parameterInfo.ParameterType == typeof(bool)) ? ((object)false) : null)));
				}
				methodInfo.Invoke(target, array);
				return true;
			}
			catch (Exception ex)
			{
				error = ((ex is TargetInvocationException { InnerException: not null } ex2) ? ex2.InnerException : ex);
				return false;
			}
		}

		private static bool CanSupply(ParameterInfo p)
		{
			if (!p.ParameterType.IsByRef)
			{
				if (!p.IsOptional && !(p.ParameterType == typeof(int)) && !(p.ParameterType == typeof(bool)))
				{
					return p.ParameterType.FullName == "UnityEngine.Sprite";
				}
				return true;
			}
			return false;
		}
	}
	public sealed class OptionalMethod
	{
		private readonly MethodInfo method;

		private readonly int suppliedCount;

		private OptionalMethod(MethodInfo method, int suppliedCount)
		{
			this.method = method;
			this.suppliedCount = suppliedCount;
		}

		public static OptionalMethod Bind(Type type, string name, Type result, params Type[] supplied)
		{
			MethodInfo methodInfo = (from m in (from m in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)
					where m.Name == name && !m.ContainsGenericParameters && m.ReturnType == result
					select m).Where(delegate(MethodInfo m)
				{
					ParameterInfo[] p = m.GetParameters();
					return p.Length >= supplied.Length && supplied.Select((Type t, int i) => p[i].ParameterType == t).All((bool x) => x) && p.Skip(supplied.Length).All((ParameterInfo x) => x.IsOptional && !x.ParameterType.IsByRef);
				})
				orderby m.GetParameters().Length
				select m).FirstOrDefault();
			if (methodInfo == null)
			{
				throw new MissingMethodException(type.FullName, name + "(" + string.Join(", ", supplied.Select((Type t) => t.Name)) + ") -> " + result.Name);
			}
			return new OptionalMethod(methodInfo, supplied.Length);
		}

		public object? Invoke(object target, params object?[] supplied)
		{
			if (supplied.Length != suppliedCount)
			{
				throw new ArgumentException("Incorrect argument count.");
			}
			ParameterInfo[] parameters = method.GetParameters();
			object[] array = new object[parameters.Length];
			Array.Copy(supplied, array, supplied.Length);
			for (int i = supplied.Length; i < array.Length; i++)
			{
				array[i] = parameters[i].DefaultValue;
			}
			try
			{
				return method.Invoke(target, array);
			}
			catch (TargetInvocationException ex) when (ex.InnerException != null)
			{
				ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
				throw;
			}
		}
	}
	public static class ChestReply
	{
		private static readonly string[] Names = new string[4] { "RPC_OpenResponse", "OpenRespons", "RPC_OpenRespons", "OpenResponse" };

		public static string? Resolve(object container, IDictionary? registered, Func<string, int> hash)
		{
			if (registered == null)
			{
				return null;
			}
			string[] names = Names;
			foreach (string text in names)
			{
				int num = hash(text);
				if (registered.Contains(num) && HandlesResponse(registered[num], container))
				{
					return text;
				}
			}
			return null;
		}

		private static bool HandlesResponse(object? handler, object container)
		{
			if (handler is Delegate action)
			{
				return Matches(action, container);
			}
			if (handler == null)
			{
				return false;
			}
			Type type = handler.GetType();
			while (type != null)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (FieldInfo fieldInfo in fields)
				{
					if (typeof(Delegate).IsAssignableFrom(fieldInfo.FieldType) && fieldInfo.GetValue(handler) is Delegate action2 && Matches(action2, container))
					{
						return true;
					}
				}
				type = type.BaseType;
			}
			return false;
		}

		private static bool Matches(Delegate action, object container)
		{
			return action.GetInvocationList().Any(delegate(Delegate callback)
			{
				MethodInfo method = callback.Method;
				ParameterInfo[] parameters = method.GetParameters();
				return callback.Target == container && (method.Name == "RPC_OpenResponse" || method.Name == "RPC_OpenRespons") && method.ReturnType == typeof(void) && parameters.Length == 2 && parameters[0].ParameterType == typeof(long) && parameters[1].ParameterType == typeof(bool);
			});
		}
	}
	public static class SettingsFile
	{
		private static readonly string[] Keys = new string[13]
		{
			"Chest.Columns", "Chest.Rows", "Reroll.Enabled", "Reroll.CostItem", "Reroll.CostAmount", "Reroll.SameChance", "Reroll.MinusChance", "Reroll.PlusChance", "Reroll.CooldownSeconds", "DailyLimits.BoardEnabled",
			"DailyLimits.BoardLimit", "DailyLimits.PlayerEnabled", "DailyLimits.PlayerLimit"
		};

		public static RerollSettings Parse(string text, bool requireComplete = true)
		{
			if (text.Length > 65536)
			{
				throw new FormatException("Config exceeds 64 KiB.");
			}
			Dictionary<string, string> values = new Dictionary<string, string>(StringComparer.Ordinal);
			string text2 = "";
			using (StringReader stringReader = new StringReader(text))
			{
				string text3;
				while ((text3 = stringReader.ReadLine()) != null)
				{
					string text4 = text3.Trim().TrimStart(new char[1] { '\ufeff' });
					if (text4.Length == 0 || text4.StartsWith("#") || text4.StartsWith(";"))
					{
						continue;
					}
					if (text4.StartsWith("["))
					{
						if (!text4.EndsWith("]"))
						{
							throw new FormatException("Incomplete config section header.");
						}
						text2 = text4.Substring(1, text4.Length - 2).Trim();
						continue;
					}
					int num = text4.IndexOf('=');
					if (num < 1)
					{
						throw new FormatException("Config lines must be comments, sections or Key = Value.");
					}
					string text5 = text2 + "." + text4.Substring(0, num).Trim();
					if (Keys.Contains(text5))
					{
						if (values.ContainsKey(text5))
						{
							throw new FormatException("Duplicate config setting: " + text5);
						}
						values.Add(text5, text4.Substring(num + 1).Trim());
					}
				}
			}
			if (requireComplete)
			{
				string[] keys = Keys;
				foreach (string text6 in keys)
				{
					if (!values.ContainsKey(text6))
					{
						throw new FormatException("Incomplete config; missing " + text6);
					}
				}
			}
			RerollSettings rerollSettings = new RerollSettings();
			rerollSettings.Columns = Number("Chest.Columns", rerollSettings.Columns);
			rerollSettings.Rows = Number("Chest.Rows", rerollSettings.Rows);
			if (!bool.TryParse(Value("Reroll.Enabled", rerollSettings.Enabled.ToString()), out rerollSettings.Enabled))
			{
				throw new FormatException("Reroll.Enabled must be true or false.");
			}
			rerollSettings.CostItem = Value("Reroll.CostItem", rerollSettings.CostItem);
			rerollSettings.CostAmount = Number("Reroll.CostAmount", rerollSettings.CostAmount);
			rerollSettings.Same = Number("Reroll.SameChance", rerollSettings.Same);
			rerollSettings.Minus = Number("Reroll.MinusChance", rerollSettings.Minus);
			rerollSettings.Plus = Number("Reroll.PlusChance", rerollSettings.Plus);
			if (!double.TryParse(Value("Reroll.CooldownSeconds", rerollSettings.CooldownSeconds.ToString(CultureInfo.InvariantCulture)), NumberStyles.Float, CultureInfo.InvariantCulture, out rerollSettings.CooldownSeconds))
			{
				throw new FormatException("Reroll.CooldownSeconds must be a number.");
			}
			if (!bool.TryParse(Value("DailyLimits.BoardEnabled", rerollSettings.BoardDailyLimitEnabled.ToString()), out rerollSettings.BoardDailyLimitEnabled) || !bool.TryParse(Value("DailyLimits.PlayerEnabled", rerollSettings.PlayerDailyLimitEnabled.ToString()), out rerollSettings.PlayerDailyLimitEnabled))
			{
				throw new FormatException("Daily limit toggles must be true or false.");
			}
			rerollSettings.BoardDailyLimit = Number("DailyLimits.BoardLimit", rerollSettings.BoardDailyLimit);
			rerollSettings.PlayerDailyLimit = Number("DailyLimits.PlayerLimit", rerollSettings.PlayerDailyLimit);
			rerollSettings.Validate();
			return rerollSettings;
			int Number(string key, int fallback)
			{
				if (!int.TryParse(Value(key, fallback.ToString(CultureInfo.InvariantCulture)), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
				{
					throw new FormatException(key + " must be an integer.");
				}
				return result;
			}
			string Value(string key, string fallback)
			{
				if (!values.TryGetValue(key, out string value))
				{
					return fallback;
				}
				return value;
			}
		}
	}
	public enum ReloadResult
	{
		None,
		Applied,
		Rejected
	}
	public sealed class LiveConfig
	{
		private string? observed;

		private string? processed;

		private double changedAt;

		private readonly double debounceSeconds;

		public RerollSettings? LastGood { get; private set; }

		public string? Error { get; private set; }

		public LiveConfig(double debounceSeconds = 0.75)
		{
			this.debounceSeconds = debounceSeconds;
		}

		public ReloadResult Prime(string text, bool allowPartial = false)
		{
			observed = (processed = text);
			return Accept(text, !allowPartial);
		}

		public ReloadResult Observe(string text, double now)
		{
			if (text != observed)
			{
				observed = text;
				changedAt = now;
				return ReloadResult.None;
			}
			if (text == processed || now - changedAt < debounceSeconds)
			{
				return ReloadResult.None;
			}
			processed = text;
			return Accept(text, complete: true);
		}

		private ReloadResult Accept(string text, bool complete)
		{
			try
			{
				RerollSettings lastGood = SettingsFile.Parse(text, complete);
				LastGood = lastGood;
				Error = null;
				return ReloadResult.Applied;
			}
			catch (Exception ex)
			{
				Error = ex.Message;
				return ReloadResult.Rejected;
			}
		}
	}
	public static class ServerConnection
	{
		public static long? CurrentPeerId(object? network)
		{
			if (network == null)
			{
				return null;
			}
			MethodInfo method = network.GetType().GetMethod("GetServerPeer", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
			if (method == null || method.ReturnType == typeof(void))
			{
				throw new MissingMethodException(network.GetType().FullName, "GetServerPeer()");
			}
			object obj = method.Invoke(network, null);
			if (obj == null)
			{
				return null;
			}
			FieldInfo field = obj.GetType().GetField("m_uid", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field == null || field.FieldType != typeof(long))
			{
				throw new MissingFieldException(obj.GetType().FullName, "Int64 m_uid");
			}
			long num = (long)field.GetValue(obj);
			if (num != 0L)
			{
				return num;
			}
			return null;
		}

		public static bool IsCurrentServer(object? network, long sender)
		{
			long? num = CurrentPeerId(network);
			if (num.HasValue)
			{
				return num.Value == sender;
			}
			return false;
		}
	}
	[DataContract]
	public sealed class QuotaEntry
	{
		[DataMember(IsRequired = true)]
		public string Id = "";

		[DataMember(IsRequired = true)]
		public string Board = "";

		[DataMember(IsRequired = true)]
		public string Player = "";

		[DataMember(IsRequired = true)]
		public string State = "reserved";

		[DataMember(IsRequired = true)]
		public int Day;

		[DataMember(IsRequired = true)]
		public double Expires;

		public QuotaEntry Copy()
		{
			return (QuotaEntry)MemberwiseClone();
		}
	}
	public sealed class QuotaResult
	{
		public string State;

		public string Message;

		public bool Changed;

		public QuotaResult(string state, string message = "", bool changed = false)
		{
			State = state;
			Message = message;
			Changed = changed;
		}
	}
	[DataContract]
	public sealed class DailyQuota
	{
		[DataMember(IsRequired = true)]
		public int Version = 1;

		[DataMember(IsRequired = true)]
		public int LatestDay = -1;

		[DataMember(IsRequired = true)]
		public Dictionary<string, QuotaEntry> Entries = new Dictionary<string, QuotaEntry>();

		public static bool Enabled(RerollSettings s)
		{
			if (!s.BoardDailyLimitEnabled)
			{
				return s.PlayerDailyLimitEnabled;
			}
			return true;
		}

		public void Validate()
		{
			if (Version != 1 || LatestDay < -1 || Entries == null || Entries.Count > 50000)
			{
				throw new InvalidOperationException("Invalid or oversized daily quota ledger.");
			}
			foreach (KeyValuePair<string, QuotaEntry> entry in Entries)
			{
				QuotaEntry value = entry.Value;
				if (value == null || entry.Key != value.Id || !Guid.TryParseExact(value.Id, "N", out var _) || string.IsNullOrEmpty(value.Board) || value.Board.Length > 80 || string.IsNullOrEmpty(value.Player) || value.Player.Length > 30 || value.Day < 0 || value.Day > LatestDay || double.IsNaN(value.Expires) || double.IsInfinity(value.Expires) || (value.State != "reserved" && value.State != "committed" && value.State != "cancelled"))
				{
					throw new InvalidOperationException("Invalid daily quota entry; preserve the ledger for recovery.");
				}
			}
		}

		public DailyQuota Copy()
		{
			return new DailyQuota
			{
				Version = Version,
				LatestDay = LatestDay,
				Entries = Entries.ToDictionary<KeyValuePair<string, QuotaEntry>, string, QuotaEntry>((KeyValuePair<string, QuotaEntry> p) => p.Key, (KeyValuePair<string, QuotaEntry> p) => p.Value.Copy())
			};
		}

		public QuotaResult Apply(string action, string id, string board, string player, int day, double now, double expires, RerollSettings settings)
		{
			Validate();
			settings.Validate();
			if (!Guid.TryParseExact(id, "N", out var _) || string.IsNullOrEmpty(board) || board.Length > 80 || string.IsNullOrEmpty(player) || player.Length > 30 || day < 0 || double.IsNaN(now) || double.IsInfinity(now) || double.IsNaN(expires) || double.IsInfinity(expires))
			{
				return new QuotaResult("denied", "Invalid daily reroll request.");
			}
			Entries.TryGetValue(id, out QuotaEntry value);
			if (value != null && (value.Board != board || value.Player != player))
			{
				return new QuotaResult("denied", "Daily reroll reservation identity mismatch.");
			}
			if (action == "release")
			{
				if (value == null || value.State == "cancelled")
				{
					return new QuotaResult("cancelled");
				}
				if (value.State == "committed")
				{
					return new QuotaResult("committed");
				}
				value.State = "cancelled";
				return new QuotaResult("cancelled", "", changed: true);
			}
			if (action != "reserve" && action != "commit")
			{
				return new QuotaResult("denied", "Unknown daily reroll operation.");
			}
			if (value?.State == "committed")
			{
				return new QuotaResult("committed");
			}
			if (value?.State == "cancelled")
			{
				re