Decompiled source of NM Passive Recharge REPO v0.3.0

BepInEx/plugins/NM_Passive_Recharge_REPO/NM_Passive_Recharge_REPO.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Nightmare.REPO.Core;
using Nightmare.REPO.Localization;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Nightmare Community / NM")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2026 Nick1Z2 (Nightmare Community / NM).")]
[assembly: AssemblyFileVersion("0.3.0.0")]
[assembly: AssemblyInformationalVersion("0.3.0")]
[assembly: AssemblyProduct("NM_Passive_Recharge_REPO")]
[assembly: AssemblyTitle("NM_Passive_Recharge_REPO")]
[assembly: AssemblyVersion("0.2.2.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 Nightmare.REPO.Localization
{
	internal static class L
	{
		internal static readonly Dictionary<string, string> Translations = new Dictionary<string, string>(StringComparer.Ordinal)
		{
			{ "Einstellungen speichern", "Save settings" },
			{ "Deaktiviert: ", "Disabled: " },
			{ "Wartet auf eingelagerte Waffen.", "Waiting for stored weapons." },
			{ "Nur als Host/Einzelspieler. Standardmäßig nur eigene Waffen; Mitspieler müssen im NM Core freigegeben werden.", "Host / single player only. By default, only your own weapons; other players must be enabled in NM Core." },
			{ "30–7200 Sekunden von leer bis voll, nach Wartezeit. Synchronisiert in ganzen Akkustrichen.", "30–7200 seconds from empty to full, after the waiting period. Synchronized in complete battery bars." },
			{ "0–300 Sekunden. Herausnehmen/Benutzen setzt Wartezeit und unvollständigen Ladestreifen zurück.", "0–300 seconds. Taking out / using an item resets the waiting period and incomplete charge bar." },
			{ "Auch andere wiederaufladbare Geräte im Inventar. Standard: ItemGun, ItemMelee, ItemStunBaton. Keine Einweg-/nicht ladbaren Batterien.", "Also recharge other rechargeable inventory devices. Default: ItemGun, ItemMelee, ItemStunBaton. Excludes disposable / unchargeable batteries." },
			{ "Eigene Waffen des Hosts aufladen. Mitspieler werden getrennt pro Spielstand freigegeben.", "Recharge the host's own weapons. Other players are enabled separately for each save." },
			{ "Volle Ladezeit für freigegebene Mitspieler, unabhängig vom Host.", "Full charge time for enabled players, independently of the host." },
			{ "Wartezeit für freigegebene Mitspieler.", "Waiting period for enabled players." },
			{ "Passive Aufladung aktiv", "Passive recharge enabled" },
			{ "Meine eigenen Waffen aufladen", "Recharge my own weapons" },
			{ "Meine Aufladung (Host)", "My recharge settings (host)" },
			{ "Sekunden für eine volle Batterie (30–7200)", "Seconds for a full battery (30–7200)" },
			{ "Wartezeit nach Einlagern (0–300 Sekunden)", "Delay after storing (0–300 seconds)" },
			{ "Auch Drohnen und andere Akku-Geräte aufladen", "Also recharge drones and other battery devices" },
			{ "Aufladung freigegebener Mitspieler", "Recharge settings for enabled players" },
			{ "Passive Aufladung", "Passive Recharge" },
			{ "Eigene Waffen und freigegebene Mitspieler getrennt aufladen.", "Separate recharge settings for your own weapons and enabled players." },
			{ "Passive Aufladung ausgeschaltet.", "Passive recharge is disabled." },
			{ "Als Mitspieler: keine Aufladung durch diesen Mod.", "As a guest: this mod does not recharge items." },
			{ "Wartet auf eine aktive Spielphase außerhalb des Shops.", "Waiting for active gameplay outside the shop." },
			{ "Gerätefehler · neuer Versuch folgt", "Device error · retry pending" },
			{ "Spieler nicht freigegeben", "Player not enabled" },
			{ "Geräteschalter aus", "Device switch off" },
			{ "in Benutzung", "in use" },
			{ "ungültiger Ladestand", "invalid charge level" },
			{ "voll", "full" },
			{ "wartet", "waiting" },
			{ "lädt", "charging" },
			{ "Gerätefehler · andere Akkus laden weiter", "Device error · other batteries keep charging" },
			{ "Aufladung eines Geräts ausgesetzt: ", "Recharge suspended for one device: " },
			{ " Waffe(n)/Gerät(e) laden gerade. Fertige Akkustriche bleiben gespeichert.", " weapon(s)/device(s) charging. Completed battery bars remain saved." },
			{ "Aufladung deaktiviert: ", "Recharge disabled: " },
			{ "Spieler", "Player" },
			{ "Freigegebene Steam-IDs für diesen Spielstand, mit Komma getrennt. Namen dienen nur der Anzeige.", "Enabled Steam IDs for this save, comma-separated. Names are for display only." },
			{ "Spielerauswahl für diesen Spielstand gespeichert.", "Player selection saved for this save." },
			{ "Auswahl konnte nicht gespeichert werden: ", "Could not save selection: " },
			{ "PASSIVE AUFLADUNG", "PASSIVE RECHARGE" },
			{ "Host-only. Aufladung kostet keine Truck-Energie. Nur eingelagert, nicht in der Hand oder am Boden. Teilfortschritt bis zum nächsten Akkustrich verfällt beim Herausnehmen.", "Host only. Recharging uses no truck energy. Items must be stored, not held or on the ground. Progress toward the next battery bar is lost when taking an item out." },
			{ "Mitspieler freigeben", "Enable other players" },
			{ "Standard: nur du. Haken werden sofort pro Spielstand gespeichert. Ausgewählte Mitspieler brauchen diesen Mod nicht. Ohne Host-Rechte bleibt die Aufladung aus.", "Default: only you. Checkboxes are saved immediately for each save. Selected players do not need this mod. Recharging stays off without host authority." },
			{ "Mitspielerauswahl verfügbar, sobald du einen Spielstand als Host geladen hast.", "Player selection is available once you have loaded a save as host." },
			{ " (du / Host – Einstellung unten)", " (you / host – setting below)" },
			{ " · Steam-ID noch nicht verfügbar", " · Steam ID not available yet" },
			{ " gespeicherte Freigabe(n), einschließlich abwesender Spieler. Wiederbeitritt wird über die Steam-ID erkannt.", " saved permission(s), including absent players. Rejoining is recognized by Steam ID." },
			{ "Alle Mitspieler-Freigaben dieses Spielstands entfernen", "Remove all player permissions for this save" },
			{ "Spielstand fehlt.", "Save is missing." },
			{ "Bitte gültige Zahlen innerhalb der angegebenen Grenzen eingeben.", "Enter valid numbers within the specified limits." },
			{ "Gespeichert. Spielregeln gelten nur, wenn du Host bist.", "Saved. Game rules apply only when you are the host." }
		};

		[ThreadStatic]
		private static string? captureLanguage;

		internal static string Language => captureLanguage ?? CoreApi.Language;

		internal static string T(string german)
		{
			if (!(Language == "de"))
			{
				return English(german);
			}
			return german;
		}

		internal static string English(string german)
		{
			if (!Translations.TryGetValue(german, out string value) || value == null)
			{
				return german;
			}
			return value;
		}

		internal static string Help(string german)
		{
			return "DE: " + german + "\nEN: " + English(german);
		}

		internal static LocalText Capture(Func<string> render)
		{
			string text = captureLanguage;
			try
			{
				captureLanguage = "de";
				string german = render();
				captureLanguage = "en";
				return new LocalText(german, render());
			}
			finally
			{
				captureLanguage = text;
			}
		}

		internal static AddonDefinition Describe(AddonDefinition definition, string name, string description)
		{
			definition.NameProvider = () => T(name);
			definition.DescriptionProvider = () => T(description);
			return definition;
		}
	}
	internal sealed class LocalText
	{
		private readonly string de;

		private readonly string en;

		internal int Length => ToString().Length;

		internal LocalText(string german, string english)
		{
			de = german;
			en = english;
		}

		public override string ToString()
		{
			if (!(L.Language == "de"))
			{
				return en;
			}
			return de;
		}

		public static implicit operator string(LocalText value)
		{
			return value.ToString();
		}

		public static implicit operator LocalText(string value)
		{
			return new LocalText(value, value);
		}
	}
}
namespace Nightmare.REPO.Truck
{
	[BepInPlugin("nightmare.repo.passiverecharge", "NM_Passive_Recharge_REPO", "0.3.0")]
	[BepInDependency("nightmare.repo.core", "2.10.1")]
	[BepInProcess("REPO.exe")]
	public sealed class Plugin : BaseUnityPlugin
	{
		private sealed class Progress
		{
			public float storedAt;

			public readonly RechargeCredit credit = new RechargeCredit();

			public float percent;

			public PlayerAvatar? owner;
		}

		private sealed class PlayerRow
		{
			public string id = "";

			public string name = "";

			public bool local;
		}

		private readonly Dictionary<ItemBattery, Progress> progress = new Dictionary<ItemBattery, Progress>();

		private readonly Dictionary<ItemBattery, float> retryAt = new Dictionary<ItemBattery, float>();

		private readonly SettingsUi settings = new SettingsUi();

		private ConfigEntry<bool> enabledMod;

		private ConfigEntry<bool> allDevices;

		private ConfigEntry<bool> ownEnabled;

		private ConfigEntry<float> seconds;

		private ConfigEntry<float> delay;

		private ConfigEntry<float> otherSeconds;

		private ConfigEntry<float> otherDelay;

		private ConfigEntry<string>? selectedEntry;

		private HashSet<string> selected = new HashSet<string>();

		private string saveScope = "";

		private readonly List<PlayerRow> players = new List<PlayerRow>();

		private AddonHandle? page;

		private float tickAt;

		private Vector2 scroll;

		private readonly List<string> itemStatus = new List<string>();

		private bool compatible;

		private LocalText status = L.Capture(() => L.T("Wartet auf eingelagerte Waffen."));

		private void Awake()
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Expected O, but got Unknown
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Expected O, but got Unknown
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Expected O, but got Unknown
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			//IL_0329: Expected O, but got Unknown
			enabledMod = ((BaseUnityPlugin)this).Config.Bind<bool>("Allgemein", "Aktiv", true, L.Help("Nur als Host/Einzelspieler. Standardmäßig nur eigene Waffen; Mitspieler müssen im NM Core freigegeben werden."));
			seconds = ((BaseUnityPlugin)this).Config.Bind<float>("Aufladung", "SekundenFuerVolleBatterie", 300f, new ConfigDescription(L.Help("30–7200 Sekunden von leer bis voll, nach Wartezeit. Synchronisiert in ganzen Akkustrichen."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(30f, 7200f), Array.Empty<object>()));
			delay = ((BaseUnityPlugin)this).Config.Bind<float>("Aufladung", "WartezeitNachEinlagern", 10f, new ConfigDescription(L.Help("0–300 Sekunden. Herausnehmen/Benutzen setzt Wartezeit und unvollständigen Ladestreifen zurück."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 300f), Array.Empty<object>()));
			allDevices = ((BaseUnityPlugin)this).Config.Bind<bool>("Aufladung", "AlleBatterieGeraete", false, L.Help("Auch andere wiederaufladbare Geräte im Inventar. Standard: ItemGun, ItemMelee, ItemStunBaton. Keine Einweg-/nicht ladbaren Batterien."));
			ownEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Allgemein", "EigeneWaffenAufladen", true, L.Help("Eigene Waffen des Hosts aufladen. Mitspieler werden getrennt pro Spielstand freigegeben."));
			otherSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Mitspieler", "SekundenFuerVolleBatterie", 300f, new ConfigDescription(L.Help("Volle Ladezeit für freigegebene Mitspieler, unabhängig vom Host."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(30f, 7200f), Array.Empty<object>()));
			otherDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Mitspieler", "WartezeitNachEinlagern", 10f, new ConfigDescription(L.Help("Wartezeit für freigegebene Mitspieler."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 300f), Array.Empty<object>()));
			settings.Toggle(enabledMod, "Passive Aufladung aktiv");
			settings.Toggle(ownEnabled, "Meine eigenen Waffen aufladen");
			settings.Heading("Meine Aufladung (Host)");
			settings.Number(seconds, "Sekunden für eine volle Batterie (30–7200)", 30f, 7200f);
			settings.Number(delay, "Wartezeit nach Einlagern (0–300 Sekunden)", 0f, 300f);
			settings.Toggle(allDevices, "Auch Drohnen und andere Akku-Geräte aufladen");
			settings.Heading("Aufladung freigegebener Mitspieler");
			settings.Number(otherSeconds, "Sekunden für eine volle Batterie (30–7200)", 30f, 7200f);
			settings.Number(otherDelay, "Wartezeit nach Einlagern (0–300 Sekunden)", 0f, 300f);
			try
			{
				Runtime.Method(typeof(ItemBattery), "BatteryFullPercentChange");
				Runtime.Field(typeof(ItemBattery), "batteryLifeInt");
				Runtime.Field(typeof(StatsManager), "saveFileCurrent");
				Runtime.Field(typeof(StatsManager), "saveFileReady");
				Runtime.Field(typeof(PlayerAvatar), "isLocal");
				Runtime.Field(typeof(PlayerAvatar), "steamID");
				Runtime.Field(typeof(PlayerAvatar), "playerName");
				page = CoreApi.Register(L.Describe(new AddonDefinition("nightmare.repo.passiverecharge", "Passive Aufladung", "0.3.0", "Eigene Waffen und freigegebene Mitspieler getrennt aufladen.", (Action<AddonUi>)Draw, 1), "Passive Aufladung", "Eigene Waffen und freigegebene Mitspieler getrennt aufladen."));
				compatible = true;
			}
			catch (Exception ex)
			{
				Exception ex2 = ex;
				Exception e = ex2;
				status = L.Capture(() => L.T("Deaktiviert: ") + e.Message);
				((BaseUnityPlugin)this).Logger.LogError((object)e);
			}
		}

		private void Update()
		{
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			if (!compatible || Time.time < tickAt)
			{
				return;
			}
			float now = Time.time;
			float num = Mathf.Min(0.5f, Math.Max(0f, now - tickAt + 0.25f));
			tickAt = now + 0.25f;
			try
			{
				RefreshPlayers();
				if (!enabledMod.Value || !Runtime.Playing || !Runtime.Host)
				{
					progress.Clear();
					itemStatus.Clear();
					status = L.Capture(() => enabledMod.Value ? (Runtime.Host ? L.T("Wartet auf eine aktive Spielphase außerhalb des Shops.") : L.T("Als Mitspieler: keine Aufladung durch diesen Mod.")) : L.T("Passive Aufladung ausgeschaltet."));
					return;
				}
				HashSet<ItemBattery> seen = new HashSet<ItemBattery>();
				int charging = 0;
				itemStatus.Clear();
				foreach (ItemBattery item in CoreSceneObjects<ItemBattery>.Get())
				{
					if (!Object.op_Implicit((Object)(object)item))
					{
						continue;
					}
					if (retryAt.TryGetValue(item, out var value) && now < value)
					{
						ItemStatus(item, L.T("Gerätefehler · neuer Versuch folgt"));
						continue;
					}
					try
					{
						if (!Object.op_Implicit((Object)(object)item))
						{
							continue;
						}
						Scene scene = ((Component)item).gameObject.scene;
						if (!((Scene)(ref scene)).IsValid())
						{
							continue;
						}
						scene = ((Component)item).gameObject.scene;
						if (!((Scene)(ref scene)).isLoaded || item.isUnchargable || item.batteryBars <= 0)
						{
							continue;
						}
						ItemEquippable component = ((Component)item).GetComponent<ItemEquippable>();
						PlayerAvatar val = (Object.op_Implicit((Object)(object)component) ? component.GetOwnerPlayerAvatar() : null);
						if (!Object.op_Implicit((Object)(object)component) || !component.IsEquipped() || (Object)(object)val == (Object)null || !Runtime.Alive(val))
						{
							continue;
						}
						bool flag = Runtime.Bool(val, "isLocal");
						string id = ((string)Runtime.Field(typeof(PlayerAvatar), "steamID").GetValue(val)) ?? "";
						if (!RechargeSelection.Allowed(flag, ownEnabled.Value, id, selected))
						{
							ItemStatus(item, L.T("Spieler nicht freigegeben"));
							continue;
						}
						if (!allDevices.Value && !Object.op_Implicit((Object)(object)((Component)item).GetComponent<ItemGun>()) && !Object.op_Implicit((Object)(object)((Component)item).GetComponent<ItemMelee>()) && !Object.op_Implicit((Object)(object)((Component)item).GetComponent<ItemStunBaton>()))
						{
							ItemStatus(item, L.T("Geräteschalter aus"));
							continue;
						}
						PhysGrabObject component2 = ((Component)item).GetComponent<PhysGrabObject>();
						if (Object.op_Implicit((Object)(object)component2) && component2.playerGrabbing.Count != 0)
						{
							ItemStatus(item, L.T("in Benutzung"));
							continue;
						}
						seen.Add(item);
						float batteryLife = item.batteryLife;
						if (float.IsNaN(batteryLife) || float.IsInfinity(batteryLife))
						{
							ItemStatus(item, L.T("ungültiger Ladestand"));
							continue;
						}
						if (!progress.TryGetValue(item, out Progress value2) || (Object)(object)value2.owner != (Object)(object)val || Math.Abs(value2.percent - batteryLife) > 0.01f)
						{
							Dictionary<ItemBattery, Progress> dictionary = progress;
							Progress obj = new Progress
							{
								storedAt = now,
								percent = batteryLife,
								owner = val
							};
							value2 = obj;
							dictionary[item] = obj;
						}
						if (batteryLife >= 100f)
						{
							value2.credit.Reset();
							ItemStatus(item, L.T("voll"));
							continue;
						}
						if (now - value2.storedAt < (flag ? delay.Value : otherDelay.Value))
						{
							ItemStatus(item, L.T("wartet"));
							continue;
						}
						charging++;
						ItemStatus(item, L.T("lädt"));
						value2.credit.Advance(num, flag ? seconds.Value : otherSeconds.Value);
						int num2 = RechargeStep.Target(batteryLife, item.batteryBars);
						double num3 = (double)num2 * (100.0 / (double)item.batteryBars) - (double)batteryLife;
						if (num2 > 0 && !(value2.credit.Percent + 1E-06 < num3))
						{
							Runtime.Method(typeof(ItemBattery), "BatteryFullPercentChange").Invoke(item, new object[2] { num2, true });
							if (Math.Abs(item.batteryLife - (float)num2 * (100f / (float)item.batteryBars)) < 0.01f)
							{
								value2.percent = item.batteryLife;
								value2.credit.Spend(num3);
							}
						}
					}
					catch (Exception ex)
					{
						progress.Remove(item);
						retryAt[item] = now + 10f;
						ItemStatus(item, L.T("Gerätefehler · andere Akkus laden weiter"));
						((BaseUnityPlugin)this).Logger.LogWarning((object)(L.T("Aufladung eines Geräts ausgesetzt: ") + ((Object)item).name + ": " + ex.Message));
					}
				}
				ItemBattery[] array = retryAt.Keys.Where((ItemBattery k) => !Object.op_Implicit((Object)(object)k) || retryAt[k] < now - 10f).ToArray();
				foreach (ItemBattery key in array)
				{
					retryAt.Remove(key);
				}
				array = progress.Keys.Where((ItemBattery k) => !Object.op_Implicit((Object)(object)k) || !seen.Contains(k)).ToArray();
				foreach (ItemBattery key2 in array)
				{
					progress.Remove(key2);
				}
				status = L.Capture(() => charging + L.T(" Waffe(n)/Gerät(e) laden gerade. Fertige Akkustriche bleiben gespeichert."));
			}
			catch (Exception ex2)
			{
				Exception ex3 = ex2;
				Exception e = ex3;
				compatible = false;
				progress.Clear();
				status = L.Capture(() => L.T("Aufladung deaktiviert: ") + e.Message);
				((BaseUnityPlugin)this).Logger.LogError((object)e);
			}
		}

		private void ItemStatus(ItemBattery battery, string text)
		{
			if (itemStatus.Count < 80)
			{
				ItemEquippable component = ((Component)battery).GetComponent<ItemEquippable>();
				PlayerAvatar val = (Object.op_Implicit((Object)(object)component) ? component.GetOwnerPlayerAvatar() : null);
				string text2 = (Object.op_Implicit((Object)(object)val) ? (((string)Runtime.Field(typeof(PlayerAvatar), "playerName").GetValue(val)) ?? L.T("Spieler")) : L.T("Spieler"));
				int num = (Object.op_Implicit((Object)(object)component) ? (Runtime.Int(component, "inventorySpotIndex") + 1) : 0);
				itemStatus.Add(text2 + " · Slot " + num + " · " + ((Object)battery).name + " · " + battery.batteryLife.ToString("0.0") + "% · " + text);
			}
		}

		private void RefreshPlayers()
		{
			players.Clear();
			bool host = Runtime.Host;
			string text = ((host && Object.op_Implicit((Object)(object)StatsManager.instance) && Object.op_Implicit((Object)(object)RunManager.instance) && !SemiFunc.IsMainMenu() && Runtime.Bool(StatsManager.instance, "saveFileReady")) ? (((string)Runtime.Field(typeof(StatsManager), "saveFileCurrent").GetValue(StatsManager.instance)) ?? "") : "");
			if (text != saveScope)
			{
				progress.Clear();
				saveScope = text;
				selectedEntry = ((text.Length == 0) ? null : ((BaseUnityPlugin)this).Config.Bind<string>("Spielerauswahl", RechargeSelection.ScopeKey(text), "", L.Help("Freigegebene Steam-IDs für diesen Spielstand, mit Komma getrennt. Namen dienen nur der Anzeige.")));
			}
			selected = RechargeSelection.Read(selectedEntry?.Value ?? "");
			if (!host || !Object.op_Implicit((Object)(object)GameDirector.instance) || SemiFunc.IsMainMenu())
			{
				return;
			}
			foreach (PlayerAvatar player in GameDirector.instance.PlayerList)
			{
				if (Object.op_Implicit((Object)(object)player))
				{
					players.Add(new PlayerRow
					{
						id = (((string)Runtime.Field(typeof(PlayerAvatar), "steamID").GetValue(player)) ?? ""),
						name = (((string)Runtime.Field(typeof(PlayerAvatar), "playerName").GetValue(player)) ?? L.T("Spieler")),
						local = Runtime.Bool(player, "isLocal")
					});
				}
			}
		}

		private void SaveSelection(HashSet<string> next)
		{
			if (selectedEntry == null || !Runtime.Host)
			{
				return;
			}
			string value = selectedEntry.Value;
			bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
			((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
			try
			{
				selectedEntry.Value = RechargeSelection.Write(next);
				((BaseUnityPlugin)this).Config.Save();
				selected = next;
				progress.Clear();
				AddonHandle? obj = page;
				if (obj != null)
				{
					obj.Notify(L.T("Spielerauswahl für diesen Spielstand gespeichert."), 8f);
				}
			}
			catch (Exception ex)
			{
				selectedEntry.Value = value;
				AddonHandle? obj2 = page;
				if (obj2 != null)
				{
					obj2.Notify(L.T("Auswahl konnte nicht gespeichert werden: ") + ex.Message, 8f);
				}
			}
			finally
			{
				((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		private void Draw(AddonUi ui)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.Label(L.T("PASSIVE AUFLADUNG"), ui.Title, Array.Empty<GUILayoutOption>());
			GUILayout.Label(L.T("Host-only. Aufladung kostet keine Truck-Energie. Nur eingelagert, nicht in der Hand oder am Boden. Teilfortschritt bis zum nächsten Akkustrich verfällt beim Herausnehmen."), ui.Notice, Array.Empty<GUILayoutOption>());
			GUILayout.Label((string)status, ui.Small, Array.Empty<GUILayoutOption>());
			scroll = GUILayout.BeginScrollView(scroll, Array.Empty<GUILayoutOption>());
			try
			{
				foreach (string item in itemStatus)
				{
					GUILayout.Label(item, ui.Small, Array.Empty<GUILayoutOption>());
				}
				GUILayout.Label(L.T("Mitspieler freigeben"), ui.Title, Array.Empty<GUILayoutOption>());
				GUILayout.Label(L.T("Standard: nur du. Haken werden sofort pro Spielstand gespeichert. Ausgewählte Mitspieler brauchen diesen Mod nicht. Ohne Host-Rechte bleibt die Aufladung aus."), ui.Body, Array.Empty<GUILayoutOption>());
				if (selectedEntry == null)
				{
					GUILayout.Label(L.T("Mitspielerauswahl verfügbar, sobald du einen Spielstand als Host geladen hast."), ui.Small, Array.Empty<GUILayoutOption>());
				}
				foreach (PlayerRow item2 in players.OrderBy<PlayerRow, string>((PlayerRow p) => p.name, StringComparer.OrdinalIgnoreCase))
				{
					if (item2.local)
					{
						GUILayout.Label(item2.name + L.T(" (du / Host – Einstellung unten)"), ui.Body, Array.Empty<GUILayoutOption>());
						continue;
					}
					bool flag = RechargeSelection.ValidId(item2.id);
					bool flag2 = flag && selected.Contains(item2.id);
					bool enabled = GUI.enabled;
					GUI.enabled = enabled && compatible && selectedEntry != null && flag;
					bool num = GUILayout.Button((flag2 ? "✓ " : "○ ") + item2.name + (flag ? (" · …" + item2.id.Substring(item2.id.Length - 6)) : L.T(" · Steam-ID noch nicht verfügbar")), ui.Button, Array.Empty<GUILayoutOption>());
					GUI.enabled = enabled;
					if (num)
					{
						HashSet<string> hashSet = new HashSet<string>(selected);
						if (flag2)
						{
							hashSet.Remove(item2.id);
						}
						else
						{
							hashSet.Add(item2.id);
						}
						SaveSelection(hashSet);
					}
				}
				if (selectedEntry != null)
				{
					GUILayout.Label(selected.Count + L.T(" gespeicherte Freigabe(n), einschließlich abwesender Spieler. Wiederbeitritt wird über die Steam-ID erkannt."), ui.Small, Array.Empty<GUILayoutOption>());
				}
				if (selectedEntry != null && selected.Count > 0 && GUILayout.Button(L.T("Alle Mitspieler-Freigaben dieses Spielstands entfernen"), ui.Button, Array.Empty<GUILayoutOption>()))
				{
					SaveSelection(new HashSet<string>());
				}
				settings.DrawRows(ui);
			}
			finally
			{
				GUILayout.EndScrollView();
			}
			settings.DrawSave(ui, ((BaseUnityPlugin)this).Config, page);
		}

		private void OnDestroy()
		{
			AddonHandle? obj = page;
			if (obj != null)
			{
				obj.Dispose();
			}
			progress.Clear();
			retryAt.Clear();
		}
	}
	internal static class RechargeSelection
	{
		public static bool ValidId(string id)
		{
			if (id != null && id.Length == 17)
			{
				return id.All((char c) => c >= '0' && c <= '9');
			}
			return false;
		}

		public static HashSet<string> Read(string text)
		{
			return new HashSet<string>((from s in (text ?? "").Split(',')
				select s.Trim()).Where(ValidId), StringComparer.Ordinal);
		}

		public static string Write(IEnumerable<string> ids)
		{
			return string.Join(",", ids.Where(ValidId).Distinct().OrderBy<string, string>((string s) => s, StringComparer.Ordinal));
		}

		public static bool Allowed(bool local, bool ownEnabled, string id, HashSet<string> selected)
		{
			if (!local)
			{
				if (ValidId(id))
				{
					return selected.Contains(id);
				}
				return false;
			}
			return ownEnabled;
		}

		public static string ScopeKey(string save)
		{
			if (string.IsNullOrWhiteSpace(save))
			{
				throw new ArgumentException(L.T("Spielstand fehlt."), "save");
			}
			using SHA256 sHA = SHA256.Create();
			return "Save_" + BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(save))).Replace("-", "").ToLowerInvariant();
		}
	}
	internal static class Policy
	{
		public static double Multiplier(double value)
		{
			if (!double.IsNaN(value) && !double.IsInfinity(value))
			{
				return Math.Max(1.0, Math.Min(20.0, value));
			}
			return 1.0;
		}

		public static double Cost(int hp, double hpPerEnergy, double multiplier)
		{
			return (double)Math.Max(0, hp) / Math.Max(1.0, hpPerEnergy) / Multiplier(multiplier);
		}

		public static int HealAmount(int health, int maximum, double credit, double energy, double ratio, double multiplier)
		{
			return Math.Max(0, Math.Min(Math.Max(0, maximum - health), (int)Math.Min(100000.0, Math.Floor(Math.Min(credit, Math.Max(0.0, energy) * Math.Max(1.0, ratio) * Multiplier(multiplier)) + 1E-07))));
		}

		public static int ExtraCrystals(int owned, int existing, int extra)
		{
			return Math.Max(0, Math.Min(Math.Max(0, extra), 10 - Math.Max(0, owned) - Math.Max(0, existing)));
		}

		public static double RestoreEnergy(double vanilla, int savedWhole, int fraction, double capacity)
		{
			int num = (int)Math.Ceiling(vanilla);
			if (savedWhole != num)
			{
				return vanilla;
			}
			return Math.Max(0.0, Math.Min(capacity, (double)num - (double)Math.Max(0, Math.Min(999999, fraction)) / 1000000.0));
		}
	}
	internal sealed class RechargeCredit
	{
		public double Percent { get; private set; }

		public void Advance(double elapsed, double seconds)
		{
			if (!double.IsNaN(elapsed) && !double.IsInfinity(elapsed) && !(seconds <= 0.0))
			{
				Percent += Math.Max(0.0, Math.Min(0.5, elapsed)) * 100.0 / seconds;
			}
		}

		public bool Ready(int bars)
		{
			if (bars > 0)
			{
				return Percent + 1E-07 >= 100.0 / (double)bars;
			}
			return false;
		}

		public void Commit(int bars)
		{
			if (bars > 0)
			{
				Percent = Math.Max(0.0, Percent - 100.0 / (double)bars);
			}
		}

		public void Spend(double amount)
		{
			if (amount > 0.0)
			{
				Percent = Math.Max(0.0, Percent - amount);
			}
		}

		public void Reset()
		{
			Percent = 0.0;
		}
	}
	internal static class RechargeStep
	{
		internal static int Target(double percent, int bars)
		{
			if (bars <= 0 || double.IsNaN(percent) || double.IsInfinity(percent) || percent >= 100.0)
			{
				return 0;
			}
			return Math.Min(bars, Math.Max(1, (int)Math.Floor(Math.Max(0.0, percent) * (double)bars / 100.0 + 1E-06) + 1));
		}
	}
	internal static class Runtime
	{
		public const string EnergyKey = "nm.truck.energy.v1";

		public static bool Host
		{
			get
			{
				if (Object.op_Implicit((Object)(object)GameManager.instance))
				{
					return SemiFunc.IsMasterClientOrSingleplayer();
				}
				return false;
			}
		}

		public static bool Playing
		{
			get
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Invalid comparison between Unknown and I4
				if (Object.op_Implicit((Object)(object)GameManager.instance) && Object.op_Implicit((Object)(object)RunManager.instance) && Object.op_Implicit((Object)(object)GameDirector.instance) && (int)GameDirector.instance.currentState == 2 && !SemiFunc.RunIsShop())
				{
					return !SemiFunc.IsMainMenu();
				}
				return false;
			}
		}

		public static float HostMultiplier
		{
			get
			{
				if (Host)
				{
					if (Chainloader.PluginInfos.TryGetValue("nightmare.repo.truckenergy", out var value))
					{
						PropertyInfo property = ((object)value.Instance).GetType().GetProperty("EffectiveMultiplier");
						if (property != null)
						{
							return (float)Policy.Multiplier(Convert.ToDouble(property.GetValue(value.Instance)));
						}
					}
					return 1f;
				}
				if (PhotonNetwork.InRoom && ((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)"nm.truck.energy.v1", out object value2) && value2 is float num)
				{
					return (float)Policy.Multiplier(num);
				}
				return 1f;
			}
		}

		public static FieldInfo Field(Type type, string name)
		{
			return AccessTools.Field(type, name) ?? throw new MissingFieldException(type.Name, name);
		}

		public static MethodInfo Method(Type type, string name)
		{
			return AccessTools.Method(type, name, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.Name, name);
		}

		public static int Int(object value, string name)
		{
			return (int)Field(value.GetType(), name).GetValue(value);
		}

		public static bool Bool(object value, string name)
		{
			return (bool)Field(value.GetType(), name).GetValue(value);
		}

		public static bool Alive(PlayerAvatar player)
		{
			if (Object.op_Implicit((Object)(object)player) && !Bool(player, "deadSet") && !Bool(player, "isDisabled") && Object.op_Implicit((Object)(object)player.playerHealth))
			{
				return Int(player.playerHealth, "health") > 0;
			}
			return false;
		}
	}
	internal static class Station
	{
		private static readonly FieldInfo balance = Runtime.Field(typeof(ChargingStation), "chargeFloat");

		private static readonly FieldInfo total = Runtime.Field(typeof(ChargingStation), "chargeTotal");

		private static readonly FieldInfo last = Runtime.Field(typeof(ChargingStation), "lastSentSegment");

		private const string SavedBase = "nmTruckEnergyBase";

		private const string SavedFraction = "nmTruckEnergyFraction";

		public static float Energy(ChargingStation station)
		{
			return Mathf.Clamp01((float)balance.GetValue(station)) * 100f;
		}

		public static Transform? Zone(ChargingStation station)
		{
			return ((Component)station).transform.Find("Charge Area");
		}

		public static void PatchPrecision(Harmony harmony)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			//IL_0047: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Expected O, but got Unknown
			harmony.Patch((MethodBase)Runtime.Method(typeof(ChargingStation), "ChargingStationSegmentChangedRPC"), new HarmonyMethod(typeof(Station), "BeforeSegment", (Type[])null), new HarmonyMethod(typeof(Station), "AfterSegment", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Runtime.Method(typeof(ChargingStation), "Start"), (HarmonyMethod)null, new HarmonyMethod(typeof(Station), "Restore", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Runtime.Method(typeof(ChargingStation), "ChargeAreaCheck"), (HarmonyMethod)null, new HarmonyMethod(typeof(Station), "Save", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)Runtime.Method(typeof(ChargingStation), "CrystalsItShouldHave"), new HarmonyMethod(typeof(Station), "BeforeCrystalCount", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static void BeforeCrystalCount(ChargingStation __instance)
		{
			if (Runtime.Host)
			{
				total.SetValue(__instance, Mathf.CeilToInt(Energy(__instance)));
			}
		}

		private static void Restore(ChargingStation __instance)
		{
			if (Runtime.Host && Object.op_Implicit((Object)(object)StatsManager.instance) && !SemiFunc.RunIsShop())
			{
				Dictionary<string, int> runStats = StatsManager.instance.runStats;
				if (runStats.TryGetValue("nmTruckEnergyBase", out var value) && runStats.TryGetValue("nmTruckEnergyFraction", out var value2))
				{
					Set(__instance, (float)Policy.RestoreEnergy(Energy(__instance), value, value2, __instance.crystals.Count * 10));
				}
			}
		}

		private static void Save(ChargingStation __instance)
		{
			if (Runtime.Host && Object.op_Implicit((Object)(object)StatsManager.instance) && !SemiFunc.RunIsShop())
			{
				float num = Energy(__instance);
				int num2 = Mathf.CeilToInt(num);
				Dictionary<string, int> runStats = StatsManager.instance.runStats;
				runStats["chargingStationChargeTotal"] = num2;
				runStats["nmTruckEnergyBase"] = num2;
				runStats["nmTruckEnergyFraction"] = Mathf.Clamp(Mathf.CeilToInt(((float)num2 - num) * 1000000f), 0, 999999);
			}
		}

		private static void BeforeSegment(ChargingStation __instance, out float __state)
		{
			__state = (Runtime.Host ? Energy(__instance) : (-1f));
		}

		private static void AfterSegment(ChargingStation __instance, float __state)
		{
			if (__state >= 0f && Runtime.Host)
			{
				Set(__instance, __state);
			}
		}

		private static void Set(ChargingStation station, float energy)
		{
			energy = Mathf.Clamp(energy, 0f, 100f);
			balance.SetValue(station, energy / 100f);
			total.SetValue(station, Mathf.CeilToInt(energy));
		}

		public static void Spend(ChargingStation station, double cost)
		{
			if (Runtime.Host && !(cost <= 0.0))
			{
				Set(station, Energy(station) - (float)cost);
				Flush(station);
			}
		}

		public static void Flush(ChargingStation station)
		{
			if (!Runtime.Host || !Object.op_Implicit((Object)(object)StatsManager.instance))
			{
				return;
			}
			float num = Energy(station);
			Save(station);
			Runtime.Method(typeof(ChargingStation), "CrystalsItShouldHave").Invoke(station, null);
			int num2 = Mathf.Clamp(Mathf.CeilToInt(num / 100f * (float)station.chargeSegments), 0, station.chargeSegments);
			if (SemiFunc.IsMultiplayer() && num2 != (int)last.GetValue(station))
			{
				PhotonView component = ((Component)station).GetComponent<PhotonView>();
				if (Object.op_Implicit((Object)(object)component) && component.ViewID != 0)
				{
					last.SetValue(station, num2);
					PhotonNetwork.RemoveBufferedRPCs(component.ViewID, "ChargingStationSegmentChangedRPC", (int[])null);
					component.RPC("ChargingStationSegmentChangedRPC", (RpcTarget)3, new object[1] { (byte)num2 });
				}
			}
		}
	}
	internal sealed class SettingsUi
	{
		private readonly List<Action<AddonUi>> rows = new List<Action<AddonUi>>();

		private readonly List<Func<bool>> valid = new List<Func<bool>>();

		private readonly List<Action> apply = new List<Action>();

		public void Heading(string label)
		{
			rows.Add(delegate(AddonUi ui)
			{
				GUILayout.Label(L.T(label), ui.Notice, Array.Empty<GUILayoutOption>());
			});
		}

		public void Number(ConfigEntry<float> entry, string label, float min, float max)
		{
			string text = entry.Value.ToString(CultureInfo.InvariantCulture);
			float value = entry.Value;
			rows.Add(delegate(AddonUi ui)
			{
				GUILayout.Label(L.T(label), ui.Body, Array.Empty<GUILayoutOption>());
				text = GUILayout.TextField(text, 12, ui.TextField, Array.Empty<GUILayoutOption>());
			});
			valid.Add(() => float.TryParse(text.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out value) && !float.IsNaN(value) && !float.IsInfinity(value) && value >= min && value <= max);
			apply.Add(delegate
			{
				entry.Value = value;
			});
		}

		public void Toggle(ConfigEntry<bool> entry, string label)
		{
			bool value = entry.Value;
			rows.Add(delegate(AddonUi ui)
			{
				if (GUILayout.Button((value ? "✓ " : "○ ") + L.T(label), ui.Button, Array.Empty<GUILayoutOption>()))
				{
					value = !value;
				}
			});
			apply.Add(delegate
			{
				entry.Value = value;
			});
		}

		public void Draw(AddonUi ui, ConfigFile config, AddonHandle? page)
		{
			DrawRows(ui);
			DrawSave(ui, config, page);
		}

		public void DrawRows(AddonUi ui)
		{
			foreach (Action<AddonUi> row in rows)
			{
				row(ui);
			}
		}

		public void DrawSave(AddonUi ui, ConfigFile config, AddonHandle? page)
		{
			if (!GUILayout.Button(L.T("Einstellungen speichern"), ui.Button, Array.Empty<GUILayoutOption>()))
			{
				return;
			}
			foreach (Func<bool> item in valid)
			{
				if (!item())
				{
					if (page != null)
					{
						page.Notify(L.T("Bitte gültige Zahlen innerhalb der angegebenen Grenzen eingeben."), 8f);
					}
					return;
				}
			}
			foreach (Action item2 in apply)
			{
				item2();
			}
			config.Save();
			if (page != null)
			{
				page.Notify(L.T("Gespeichert. Spielregeln gelten nur, wenn du Host bist."), 8f);
			}
		}
	}
}