Decompiled source of Penumbra v1.1.5

Penumbra.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Text;
using Microsoft.CodeAnalysis;
using Penumbra.Resources;
using Penumbra.Services;
using ProjectM;
using ProjectM.Gameplay.Scripting;
using ProjectM.Gameplay.WarEvents;
using ProjectM.Network;
using ProjectM.Physics;
using ProjectM.Scripting;
using ProjectM.Shared;
using Stunlock.Core;
using Stunlock.Network;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using VampireCommandFramework;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("Penumbra")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.5.0")]
[assembly: AssemblyInformationalVersion("1.1.5")]
[assembly: AssemblyProduct("Penumbra")]
[assembly: AssemblyTitle("Penumbra")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.5.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 Penumbra
{
	internal static class Buffs
	{
		private static EntityManager EntityManager => Core.EntityManager;

		private static ServerGameManager ServerGameManager => Core.ServerGameManager;

		private static DebugEventsSystem DebugEventsSystem => Core.DebugEventsSystem;

		public static bool TryApplyBuff(this Entity entity, PrefabGUID buffPrefabGuid)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			if (!entity.HasBuff(buffPrefabGuid))
			{
				ApplyBuffDebugEvent val = default(ApplyBuffDebugEvent);
				val.BuffPrefabGUID = buffPrefabGuid;
				ApplyBuffDebugEvent val2 = val;
				FromCharacter val3 = default(FromCharacter);
				val3.Character = entity;
				val3.User = entity;
				FromCharacter val4 = val3;
				DebugEventsSystem.ApplyBuff(val4, val2);
				return true;
			}
			return false;
		}

		public static bool TryGetBuff(this Entity entity, PrefabGUID buffPrefabGUID, out Entity buffEntity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			ServerGameManager serverGameManager = ServerGameManager;
			if (((ServerGameManager)(ref serverGameManager)).TryGetBuff(entity, ((PrefabGUID)(ref buffPrefabGUID)).ToIdentifier(), ref buffEntity))
			{
				return true;
			}
			return false;
		}

		public static bool TryRemoveBuff(this Entity entity, PrefabGUID buffPrefabGuid)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (entity.TryGetBuff(buffPrefabGuid, out var buffEntity))
			{
				DestroyUtility.Destroy(EntityManager, buffEntity, (DestroyDebugReason)13, (string)null, 0);
				return true;
			}
			return false;
		}

		public static bool TryApplyAndGetBuff(this Entity entity, PrefabGUID buffPrefabGuid, out Entity buffEntity)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			buffEntity = Entity.Null;
			if (entity.TryApplyBuff(buffPrefabGuid) && entity.TryGetBuff(buffPrefabGuid, out buffEntity))
			{
				return true;
			}
			return false;
		}
	}
	internal static class Core
	{
		private static MonoBehaviour _monoBehaviour;

		private static readonly Dictionary<PrefabGUID, string> _prefabGuidsToNames = new Dictionary<PrefabGUID, string>();

		public static bool _initialized;

		public static World Server { get; } = GetServerWorld() ?? throw new Exception("There is no Server world!");


		public static EntityManager EntityManager => Server.EntityManager;

		public static ServerGameManager ServerGameManager => ServerScriptMapper.GetServerGameManager();

		public static PrefabCollectionSystem PrefabCollectionSystem { get; internal set; }

		public static ServerGameSettingsSystem ServerGameSettingsSystem { get; internal set; }

		public static ServerScriptMapper ServerScriptMapper { get; internal set; }

		public static DebugEventsSystem DebugEventsSystem { get; internal set; }

		public static EntityCommandBufferSystem EntityCommandBufferSystem { get; internal set; }

		public static Singleton NetworkIdSystem { get; internal set; }

		public static double ServerTime => ServerGameManager.ServerTime;

		public static ManualLogSource Log => Plugin.LogInstance;

		public static IReadOnlyDictionary<PrefabGUID, string> PrefabGuidsToNames => _prefabGuidsToNames;

		public static void Initialize()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			if (!_initialized)
			{
				PrefabCollectionSystem = Server.GetExistingSystemManaged<PrefabCollectionSystem>();
				ServerGameSettingsSystem = Server.GetExistingSystemManaged<ServerGameSettingsSystem>();
				DebugEventsSystem = Server.GetExistingSystemManaged<DebugEventsSystem>();
				ServerScriptMapper = Server.GetExistingSystemManaged<ServerScriptMapper>();
				EntityCommandBufferSystem = Server.GetExistingSystemManaged<EntityCommandBufferSystem>();
				NetworkIdSystem = ((ComponentSystemBase)ServerScriptMapper).GetSingleton<Singleton>();
				InitializePrefabGuidNames();
				if (Plugin._tokensConfig.TokenSystem || Plugin._tokensConfig.DailyLogin)
				{
					TokenService.Initialize();
				}
				new LocalizationService();
				new MerchantService();
				_initialized = true;
			}
		}

		private static World GetServerWorld()
		{
			return ((IEnumerable<World>)World.s_AllWorlds.ToArray()).FirstOrDefault((Func<World, bool>)((World world) => world.Name == "Server"));
		}

		private static void InitializePrefabGuidNames()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<string, PrefabGUID> enumerator = PrefabCollectionSystem.SpawnableNameToPrefabGuidDictionary.GetEnumerator();
			while (enumerator.MoveNext())
			{
				KeyValuePair<string, PrefabGUID> current = enumerator.Current;
				_prefabGuidsToNames[current.Value] = current.Key;
			}
		}

		public static void StartCoroutine(IEnumerator routine)
		{
			//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_0027: Expected O, but got Unknown
			if ((Object)(object)_monoBehaviour == (Object)null)
			{
				GameObject val = new GameObject("Penumbra");
				_monoBehaviour = (MonoBehaviour)(object)val.AddComponent<IgnorePhysicsDebugSystem>();
				Object.DontDestroyOnLoad((Object)val);
			}
			_monoBehaviour.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(routine));
		}
	}
	internal static class GenerateREADME
	{
		private static readonly Regex _commandGroupRegex = new Regex("\\[CommandGroup\\(name:\\s*\"(?<group>[^\"]+)\",\\s*\"(?<short>[^\"]+)\"\\)\\]");

		private static readonly Regex _commandGroupAndShortRegex = new Regex("\\[CommandGroup\\(name:\\s*\"(?<group>[^\"]+)\"(?:\\s*,\\s*short:\\s*\"(?<short>[^\"]+)\")?\\)\\]");

		private static readonly Regex _commandAttributeRegex = new Regex("\\[Command\\(name:\\s*\"(?<name>[^\"]+)\"(?:,\\s*shortHand:\\s*\"(?<shortHand>[^\"]+)\")?(?:,\\s*adminOnly:\\s*(?<adminOnly>\\w+))?(?:,\\s*usage:\\s*\"(?<usage>[^\"]+)\")?(?:,\\s*description:\\s*\"(?<description>[^\"]+)\")?\\)\\]");

		private const string COMMANDS_HEADER = "## Commands";

		private const string CONFIG_HEADER = "## Configuration";

		private static readonly Dictionary<(string groupName, string groupShort), List<(string name, string shortHand, bool adminOnly, string usage, string description)>> _commandsByGroup = new Dictionary<(string, string), List<(string, string, bool, string, string)>>();

		private static string CommandsPath { get; set; }

		private static string ReadMePath { get; set; }

		public static void Main(string[] args)
		{
			if (Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true")
			{
				Console.WriteLine("GenerateREADME skipped during GitHub Actions build.");
				return;
			}
			if (args.Length < 2)
			{
				Console.WriteLine("Usage: GenerateREADME <CommandsPath> <ReadMePath>");
				return;
			}
			CommandsPath = args[0];
			ReadMePath = args[1];
			try
			{
				Generate();
				Console.WriteLine("README generated successfully.");
			}
			catch (Exception ex)
			{
				Console.WriteLine("Error generating README: " + ex.Message);
			}
		}

		private static void Generate()
		{
			CollectCommands();
			UpdateReadme(BuildCommandsSection());
		}

		private static void CollectCommands()
		{
			foreach (string item6 in from file in Directory.GetFiles(CommandsPath, "*.cs")
				where !Path.GetFileName(file).Equals("DevCommands.cs", StringComparison.OrdinalIgnoreCase)
				select file)
			{
				string input = File.ReadAllText(item6);
				Match match = _commandGroupRegex.Match(input);
				if (!match.Success)
				{
					match = _commandGroupAndShortRegex.Match(input);
				}
				string item;
				string item2;
				if (match.Success)
				{
					item = match.Groups["group"].Value;
					item2 = match.Groups["short"].Value;
				}
				else
				{
					item = "misc";
					item2 = string.Empty;
				}
				if (!_commandsByGroup.TryGetValue((item, item2), out List<(string, string, bool, string, string)> value))
				{
					value = new List<(string, string, bool, string, string)>();
					_commandsByGroup[(item, item2)] = value;
				}
				foreach (Match item7 in _commandAttributeRegex.Matches(input))
				{
					string value2 = item7.Groups["name"].Value;
					string item3 = (item7.Groups["shortHand"].Success ? item7.Groups["shortHand"].Value : string.Empty);
					bool result = false;
					if (item7.Groups["adminOnly"].Success)
					{
						bool.TryParse(item7.Groups["adminOnly"].Value, out result);
					}
					string item4 = (item7.Groups["usage"].Success ? item7.Groups["usage"].Value : string.Empty);
					string item5 = (item7.Groups["description"].Success ? item7.Groups["description"].Value : string.Empty);
					value.Add((value2, item3, result, item4, item5));
				}
			}
		}

		private static string BuildCommandsSection()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("## Commands");
			List<(string, string)> list = _commandsByGroup.Keys.OrderBy(((string groupName, string groupShort) g) => g.groupName).ToList();
			foreach (var item6 in list)
			{
				var (text, text2) = item6;
				foreach (var item7 in _commandsByGroup[item6])
				{
					string item = item7.name;
					string item2 = item7.shortHand;
					bool item3 = item7.adminOnly;
					string item4 = item7.usage;
					string item5 = item7.description;
					bool flag = !string.IsNullOrEmpty(item2);
					bool num = !string.IsNullOrEmpty(text2);
					string text3 = (string.IsNullOrEmpty(item4) ? item : item4);
					string text4 = ((text3.EndsWith(item) || !flag) ? item : string.Empty);
					string value = (item3 ? " \ud83d\udd12" : string.Empty);
					string empty = string.Empty;
					empty = ((!num) ? (flag ? text3.Replace("." + text + " " + item2, "") : text3.Replace("." + text + " " + text4, "")) : (flag ? text3.Replace("." + text2 + " " + item2, "") : text3.Replace("." + text2 + " " + text4, "")));
					string value2 = $"- `.{text} {item}{empty}`{value}";
					stringBuilder.AppendLine(value2);
					StringBuilder stringBuilder2;
					StringBuilder.AppendInterpolatedStringHandler handler;
					if (!string.IsNullOrEmpty(item5))
					{
						stringBuilder2 = stringBuilder;
						StringBuilder stringBuilder3 = stringBuilder2;
						handler = new StringBuilder.AppendInterpolatedStringHandler(4, 1, stringBuilder2);
						handler.AppendLiteral("  - ");
						handler.AppendFormatted(item5);
						stringBuilder3.AppendLine(ref handler);
					}
					stringBuilder2 = stringBuilder;
					StringBuilder stringBuilder4 = stringBuilder2;
					handler = new StringBuilder.AppendInterpolatedStringHandler(16, 1, stringBuilder2);
					handler.AppendLiteral("  - Shortcut: *");
					handler.AppendFormatted(text3);
					handler.AppendLiteral("*");
					stringBuilder4.AppendLine(ref handler);
				}
				if (list.IndexOf(item6) < list.Count - 1)
				{
					stringBuilder.AppendLine();
				}
			}
			return stringBuilder.ToString();
		}

		private static void UpdateReadme(string commandsSection)
		{
			bool flag = false;
			bool flag2 = false;
			List<string> list = new List<string>();
			try
			{
				foreach (string item in File.ReadLines(ReadMePath))
				{
					if (item.Trim().Equals("## Commands", StringComparison.OrdinalIgnoreCase))
					{
						flag = true;
						flag2 = true;
						list.Add(commandsSection);
						continue;
					}
					if (flag && item.Trim().StartsWith("## ", StringComparison.OrdinalIgnoreCase) && !item.Trim().Equals("## Commands", StringComparison.OrdinalIgnoreCase))
					{
						flag = false;
					}
					if (!flag)
					{
						list.Add(item);
					}
				}
				if (!flag2)
				{
					list.Add("## Commands");
					list.Add(commandsSection);
				}
				File.WriteAllLines(ReadMePath, list);
			}
			catch (Exception ex)
			{
				Console.Error.WriteLine("Error updating the readme: " + ex.Message);
				throw;
			}
		}

		private static string Capitalize(string input)
		{
			if (!string.IsNullOrEmpty(input))
			{
				return char.ToUpper(input[0]) + input.Substring(1, input.Length - 1);
			}
			return input;
		}
	}
	[BepInPlugin("io.zfolmt.Penumbra", "Penumbra", "1.1.5")]
	internal class Plugin : BasePlugin
	{
		public class TokensConfig
		{
			public bool TokenSystem { get; }

			public PrefabGUID TokenItem { get; }

			public int TokenRatio { get; }

			public int TokenRate { get; }

			public bool DailyLogin { get; }

			public PrefabGUID DailyItem { get; }

			public int DailyQuantity { get; }

			public int UpdateInterval { get; }

			public TokensConfig()
			{
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_004a: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
				TokenSystem = InitConfigEntry("Tokens", "EnableTokens", defaultValue: false, "Enable or disable token system.").Value;
				TokenItem = new PrefabGUID(InitConfigEntry("Tokens", "TokenItemReward", 576389135, "Item prefab for currency reward.").Value);
				TokenRatio = InitConfigEntry("Tokens", "TokenItemRatio", 6, "Currency/reward factor.").Value;
				TokenRate = InitConfigEntry("Tokens", "TokensPerMinute", 5, "Tokens gained per minute online.").Value;
				DailyLogin = InitConfigEntry("Tokens", "DailyLogin", defaultValue: false, "Enable or disable daily login incentive.").Value;
				DailyItem = new PrefabGUID(InitConfigEntry("Tokens", "DailyItemReward", -257494203, "Item prefab for daily reward.").Value);
				DailyQuantity = InitConfigEntry("Tokens", "DailyItemQuantity", 50, "Amount rewarded for daily login.").Value;
				UpdateInterval = InitConfigEntry("Tokens", "TokenUpdateInterval", 30, "Minutes between updates.").Value;
			}
		}

		public class MerchantConfig
		{
			public string Name;

			public string[] OutputItems;

			public int[] OutputAmounts;

			public string[] InputItems;

			public int[] InputAmounts;

			public int[] StockAmounts;

			public int RestockTime;

			public int TraderPrefab;

			public string Position;

			public bool Roam;
		}

		private Harmony _harmony;

		private static readonly string _tokensPath = Path.Combine(Paths.ConfigPath, "Penumbra", "player_tokens.json");

		private static readonly string _pluginPath = Path.Combine(Paths.ConfigPath, "Penumbra");

		public static TokensConfig _tokensConfig;

		private static readonly List<MerchantConfig> _merchants = new List<MerchantConfig>();

		internal static Plugin Instance { get; set; }

		public static Harmony Harmony => Instance._harmony;

		public static ManualLogSource LogInstance => ((BasePlugin)Instance).Log;

		public static string TokensPath => _tokensPath;

		public static List<MerchantConfig> Merchants => _merchants;

		public override void Load()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Expected O, but got Unknown
			Instance = this;
			_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
			InitConfig();
			CommandRegistry.RegisterAll();
			ManualLogSource log = Core.Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(10, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("Penumbra");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("1.1.5");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("] loaded!");
			}
			log.LogInfo(val);
		}

		private static void CreateDirectory(string path)
		{
			if (!Directory.Exists(path))
			{
				Directory.CreateDirectory(path);
			}
		}

		private void InitConfig()
		{
			CreateDirectory(_pluginPath);
			_tokensConfig = new TokensConfig();
			TokenService.LoadTokens();
			LoadMerchants();
			if (_merchants.Count == 0)
			{
				CreateDefaultMerchants();
			}
			SaveMerchants();
		}

		public static ConfigEntry<T> InitConfigEntry<T>(string section, string key, T defaultValue, string description)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			ConfigEntry<T> val = ((BasePlugin)Instance).Config.Bind<T>(section, key, defaultValue, description);
			string text = Path.Combine(Paths.ConfigPath, "io.zfolmt.Penumbra.cfg");
			ConfigEntry<T> val2 = default(ConfigEntry<T>);
			if (File.Exists(text) && new ConfigFile(text, true).TryGetEntry<T>(section, key, ref val2))
			{
				val.Value = val2.Value;
			}
			return val;
		}

		private void LoadMerchants()
		{
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Expected O, but got Unknown
			int num = 0;
			while (true)
			{
				string text = $"Merchant{num + 1}";
				ConfigEntry<string> val = ((BasePlugin)this).Config.Bind<string>(text, "OutputItems", "", "Comma-separated item prefab IDs for output");
				if (string.IsNullOrEmpty(val.Value))
				{
					break;
				}
				MerchantConfig item = new MerchantConfig
				{
					Name = ((BasePlugin)this).Config.Bind<string>(text, "Name", "", "Name of merchant/wares").Value,
					OutputItems = val.Value.Split(','),
					OutputAmounts = ParseIntArray(((BasePlugin)this).Config.Bind<string>(text, "OutputAmounts", "", "Amounts for each output item.").Value),
					InputItems = ((BasePlugin)this).Config.Bind<string>(text, "InputItems", "", "Comma-separated item prefab IDs for input.").Value.Split(','),
					InputAmounts = ParseIntArray(((BasePlugin)this).Config.Bind<string>(text, "InputAmounts", "", "Amounts for each input item.").Value),
					StockAmounts = ParseIntArray(((BasePlugin)this).Config.Bind<string>(text, "StockAmounts", "", "Stock amounts for each output item.").Value),
					RestockTime = ((BasePlugin)this).Config.Bind<int>(text, "RestockTime", 60, "Restock time in minutes").Value,
					Roam = ((BasePlugin)this).Config.Bind<bool>(text, "Roam", false, "Pace around or stay put.").Value,
					TraderPrefab = ((BasePlugin)this).Config.Bind<int>(text, "TraderPrefab", 0, "Trader prefab ID").Value,
					Position = ((BasePlugin)this).Config.Bind<string>(text, "Position", "", "Position of merchant spawn in world.").Value
				};
				_merchants.Add(item);
				num++;
			}
			ManualLogSource logInstance = LogInstance;
			bool flag = default(bool);
			BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(18, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Loaded ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(_merchants.Count);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" merchants!");
			}
			logInstance.LogWarning(val2);
		}

		private static int[] ParseIntArray(string value)
		{
			List<int> list = new List<int>();
			int result;
			foreach (int item in from v in value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries)
				select int.TryParse(v, out result) ? result : 0)
			{
				list.Add(item);
			}
			return list.ToArray();
		}

		private static void CreateDefaultMerchants()
		{
			_merchants.Add(new MerchantConfig
			{
				Name = "MerchantOne",
				OutputItems = new string[16]
				{
					"1247086852", "-1619308732", "2019195024", "-222860772", "950358400", "220001518", "124616797", "1954207008", "-1930402723", "1801132968",
					"1630030026", "-915028618", "1102277512", "1272855317", "781586362", "2099198078"
				},
				OutputAmounts = new int[16]
				{
					1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
					1, 1, 1, 1, 1, 1
				},
				InputItems = new string[16]
				{
					"-182923609", "-1629804427", "1334469825", "1488205677", "-77477508", "-77477508", "-77477508", "-77477508", "-77477508", "-77477508",
					"-77477508", "-77477508", "-77477508", "-77477508", "-77477508", "-77477508"
				},
				InputAmounts = new int[16]
				{
					3, 3, 3, 3, 1, 1, 1, 1, 1, 1,
					1, 1, 1, 1, 1, 1
				},
				StockAmounts = new int[16]
				{
					1, 1, 1, 1, 5, 5, 5, 5, 5, 5,
					5, 5, 5, 5, 5, 5
				},
				RestockTime = 60,
				Roam = false,
				TraderPrefab = 0,
				Position = ""
			});
			_merchants.Add(new MerchantConfig
			{
				Name = "MerchantTwo",
				OutputItems = new string[9] { "28358550", "28358550", "28358550", "28358550", "28358550", "28358550", "28358550", "28358550", "28358550" },
				OutputAmounts = new int[9] { 250, 250, 250, 250, 250, 125, 125, 100, 100 },
				InputItems = new string[9] { "-21943750", "666638454", "-1260254082", "-1581189572", "551949280", "-1461326411", "1655869633", "1262845777", "2085163661" },
				InputAmounts = new int[9] { 1, 1, 1, 1, 5, 5, 5, 500, 500 },
				StockAmounts = new int[9] { 99, 99, 99, 99, 99, 99, 99, 99, 99 },
				RestockTime = 60,
				Roam = false,
				TraderPrefab = 0,
				Position = ""
			});
			MerchantConfig merchantConfig = new MerchantConfig();
			merchantConfig.Name = "MerchantThree";
			merchantConfig.OutputItems = new string[20]
			{
				"-2128818978", "-1988816037", "-1607893829", "238268650", "409678749", "607559019", "-2073081569", "1780339680", "-262204844", "-548847761",
				"-1797796642", "1587354182", "-1785271534", "1863126275", "584164197", "379281083", "136740861", "-1814109557", "821609569", "-1755568324"
			};
			MerchantConfig merchantConfig2 = merchantConfig;
			List<int> list = new List<int>();
			foreach (int item in Enumerable.Repeat(1, 20))
			{
				list.Add(item);
			}
			merchantConfig2.OutputAmounts = list.ToArray();
			MerchantConfig merchantConfig3 = merchantConfig;
			List<string> list2 = new List<string>();
			foreach (string item2 in Enumerable.Repeat("-257494203", 20))
			{
				list2.Add(item2);
			}
			merchantConfig3.InputItems = list2.ToArray();
			merchantConfig.InputAmounts = new int[20]
			{
				300, 300, 300, 300, 300, 300, 300, 300, 300, 300,
				300, 300, 300, 500, 500, 500, 500, 500, 500, 500
			};
			MerchantConfig merchantConfig4 = merchantConfig;
			List<int> list3 = new List<int>();
			foreach (int item3 in Enumerable.Repeat(99, 20))
			{
				list3.Add(item3);
			}
			merchantConfig4.StockAmounts = list3.ToArray();
			merchantConfig.RestockTime = 60;
			merchantConfig.Roam = false;
			merchantConfig.TraderPrefab = 0;
			merchantConfig.Position = "";
			_merchants.Add(merchantConfig);
			_merchants.Add(new MerchantConfig
			{
				Name = "MerchantFour",
				OutputItems = new string[4] { "-257494203", "-257494203", "-257494203", "-257494203" },
				OutputAmounts = new int[4] { 50, 75, 100, 150 },
				InputItems = new string[4] { "-456161884", "988417522", "-1787563914", "805157024" },
				InputAmounts = new int[4] { 250, 250, 250, 250 },
				StockAmounts = new int[4] { 99, 99, 99, 99 },
				RestockTime = 60,
				Roam = false,
				TraderPrefab = 0,
				Position = ""
			});
			_merchants.Add(new MerchantConfig
			{
				Name = "MerchantFive",
				OutputItems = new string[5] { "-1370210913", "1915695899", "862477668", "429052660", "28358550" },
				OutputAmounts = new int[5] { 1, 1, 1500, 15, 250 },
				InputItems = new string[5] { "-257494203", "-257494203", "-257494203", "-257494203", "-257494203" },
				InputAmounts = new int[5] { 250, 250, 250, 250, 250 },
				StockAmounts = new int[5] { 99, 99, 99, 99, 99 },
				RestockTime = 60,
				Roam = false,
				TraderPrefab = 0,
				Position = ""
			});
			LogInstance.LogWarning((object)"Created default merchants!");
		}

		private void SaveMerchants()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			foreach (ConfigDefinition item in ((BasePlugin)this).Config.Keys.Where((ConfigDefinition k) => k.Section.StartsWith("Merchant", StringComparison.Ordinal)).ToList())
			{
				((BasePlugin)this).Config.Remove(new ConfigDefinition(item.Section, item.Key));
			}
			for (int i = 0; i < _merchants.Count; i++)
			{
				string text = $"Merchant{i + 1}";
				MerchantConfig merchantConfig = _merchants[i];
				((BasePlugin)this).Config.Bind<string>(text, "Name", merchantConfig.Name, "Name of merchant/wares.");
				((BasePlugin)this).Config.Bind<string>(text, "OutputItems", string.Join(",", merchantConfig.OutputItems), "Comma-separated item prefab IDs for output.");
				((BasePlugin)this).Config.Bind<string>(text, "OutputAmounts", string.Join(",", merchantConfig.OutputAmounts), "Amounts for each output item.");
				((BasePlugin)this).Config.Bind<string>(text, "InputItems", string.Join(",", merchantConfig.InputItems), "Comma-separated item prefab IDs for input.");
				((BasePlugin)this).Config.Bind<string>(text, "InputAmounts", string.Join(",", merchantConfig.InputAmounts), "Amounts for each input item.");
				((BasePlugin)this).Config.Bind<string>(text, "StockAmounts", string.Join(",", merchantConfig.StockAmounts), "Stock amounts for each output item.");
				((BasePlugin)this).Config.Bind<int>(text, "RestockTime", merchantConfig.RestockTime, "Restock time in minutes.");
				((BasePlugin)this).Config.Bind<bool>(text, "Roam", merchantConfig.Roam, "Pace around or stay put.");
				((BasePlugin)this).Config.Bind<int>(text, "TraderPrefab", merchantConfig.TraderPrefab, "Trader prefab for merchant.");
				((BasePlugin)this).Config.Bind<string>(text, "Position", merchantConfig.Position, "Position of merchant spawn in world.");
			}
		}

		public void UpdateMerchantDefinition(int merchantIndex, int traderGuid, float3 position)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: 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)
			if (merchantIndex >= 0 && merchantIndex < _merchants.Count)
			{
				MerchantConfig merchantConfig = _merchants[merchantIndex];
				merchantConfig.TraderPrefab = traderGuid;
				merchantConfig.Position = $"{position.x},{position.y},{position.z}";
				SaveMerchants();
			}
		}

		public override bool Unload()
		{
			((BasePlugin)this).Config.Clear();
			_harmony.UnpatchSelf();
			return true;
		}
	}
	internal static class VExtensions
	{
		public delegate void WithRefHandler<T>(ref T item);

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public readonly struct NativeAccessor<T> : IDisposable where T : unmanaged
		{
			private static NativeArray<T> _array;

			public T this[int index]
			{
				get
				{
					return _array[index];
				}
				set
				{
					_array[index] = value;
				}
			}

			public int Length => _array.Length;

			public NativeAccessor(NativeArray<T> array)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				_array = array;
			}

			public Enumerator<T> GetEnumerator()
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				return _array.GetEnumerator();
			}

			public void Dispose()
			{
				_array.Dispose();
			}
		}

		private const string EMPTY_KEY = "LocalizationKey.Empty";

		private static EntityManager EntityManager => Core.EntityManager;

		private static ServerGameManager ServerGameManager => Core.ServerGameManager;

		public static void With<T>(this Entity entity, WithRefHandler<T> action) where T : struct
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: 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)
			T item = entity.ReadRW<T>();
			action(ref item);
			EntityManager entityManager = EntityManager;
			((EntityManager)(ref entityManager)).SetComponentData<T>(entity, item);
		}

		public static void AddWith<T>(this Entity entity, WithRefHandler<T> action) where T : struct
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: 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)
			if (!entity.Has<T>())
			{
				entity.Add<T>();
			}
			entity.With(action);
		}

		public unsafe static void Write<T>(this Entity entity, T componentData) where T : struct
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			TypeIndex typeIndex = new ComponentType(Il2CppType.Of<T>(), (AccessMode)0).TypeIndex;
			byte[] array = StructureToByteArray(componentData);
			int num = Marshal.SizeOf<T>();
			fixed (byte* ptr = array)
			{
				EntityManager entityManager = EntityManager;
				((EntityManager)(ref entityManager)).SetComponentDataRaw(entity, typeIndex, (void*)ptr, num);
			}
		}

		private static byte[] StructureToByteArray<T>(T structure) where T : struct
		{
			int num = Marshal.SizeOf(structure);
			byte[] array = new byte[num];
			IntPtr intPtr = Marshal.AllocHGlobal(num);
			Marshal.StructureToPtr(structure, intPtr, fDeleteOld: true);
			Marshal.Copy(intPtr, array, 0, num);
			Marshal.FreeHGlobal(intPtr);
			return array;
		}

		private unsafe static T ReadRW<T>(this Entity entity) where T : struct
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			TypeIndex typeIndex = new ComponentType(Il2CppType.Of<T>(), (AccessMode)0).TypeIndex;
			EntityManager entityManager = EntityManager;
			return Marshal.PtrToStructure<T>(new IntPtr(((EntityManager)(ref entityManager)).GetComponentDataRawRW(entity, typeIndex)));
		}

		public unsafe static T Read<T>(this Entity entity) where T : struct
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			TypeIndex typeIndex = new ComponentType(Il2CppType.Of<T>(), (AccessMode)0).TypeIndex;
			EntityManager entityManager = EntityManager;
			return Marshal.PtrToStructure<T>(new IntPtr(((EntityManager)(ref entityManager)).GetComponentDataRawRO(entity, typeIndex)));
		}

		public static DynamicBuffer<T> ReadBuffer<T>(this Entity entity) where T : struct
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = EntityManager;
			return ((EntityManager)(ref entityManager)).GetBuffer<T>(entity, false);
		}

		public static bool TryGetComponent<T>(this Entity entity, out T componentData) where T : struct
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			componentData = default(T);
			if (entity.Has<T>())
			{
				componentData = entity.Read<T>();
				return true;
			}
			return false;
		}

		public static bool TryRemoveComponent<T>(this Entity entity) where T : struct
		{
			//IL_0000: 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)
			if (entity.Has<T>())
			{
				entity.Remove<T>();
				return true;
			}
			return false;
		}

		public static bool Has<T>(this Entity entity) where T : struct
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = EntityManager;
			return ((EntityManager)(ref entityManager)).HasComponent(entity, new ComponentType(Il2CppType.Of<T>(), (AccessMode)0));
		}

		public static bool Has(this Entity entity, ComponentType componentType)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = EntityManager;
			return ((EntityManager)(ref entityManager)).HasComponent(entity, componentType);
		}

		public static string GetPrefabName(this PrefabGUID prefabGuid)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (!LocalizationService.PrefabGuidNames.TryGetValue(prefabGuid, out var value))
			{
				return "LocalizationKey.Empty";
			}
			return $"{value} {prefabGuid}";
		}

		public static string GetLocalizedName(this PrefabGUID prefabGuid)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			string value = LocalizationService.GetNameFromPrefabGuid(prefabGuid);
			if (!string.IsNullOrEmpty(value))
			{
				return value;
			}
			if (LocalizationService.PrefabGuidNames.TryGetValue(prefabGuid, out value))
			{
				return value;
			}
			return "LocalizationKey.Empty";
		}

		public static void Add<T>(this Entity entity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = EntityManager;
			((EntityManager)(ref entityManager)).AddComponent(entity, new ComponentType(Il2CppType.Of<T>(), (AccessMode)0));
		}

		public static void Add(this Entity entity, ComponentType componentType)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = EntityManager;
			((EntityManager)(ref entityManager)).AddComponent(entity, componentType);
		}

		public static void Remove<T>(this Entity entity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			EntityManager entityManager = EntityManager;
			((EntityManager)(ref entityManager)).RemoveComponent(entity, new ComponentType(Il2CppType.Of<T>(), (AccessMode)0));
		}

		public static bool IsTrader(this Entity entity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if (entity.Has<Trader>())
			{
				return true;
			}
			return false;
		}

		public static bool IsMerchant(this Entity entity)
		{
			//IL_0000: 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)
			if (entity.Has<Trader>() && entity.Has<Immortal>())
			{
				return true;
			}
			return false;
		}

		public static bool Exists(this Entity entity)
		{
			//IL_0000: 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)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if (entity.HasValue())
			{
				EntityManager entityManager = EntityManager;
				return ((EntityManager)(ref entityManager)).Exists(entity);
			}
			return false;
		}

		public static bool HasValue(this Entity entity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return entity != Entity.Null;
		}

		public static NetworkId GetNetworkId(this Entity entity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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)
			if (entity.TryGetComponent<NetworkId>(out NetworkId componentData))
			{
				return componentData;
			}
			return NetworkId.Empty;
		}

		public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
		{
			foreach (T item in source)
			{
				action(item);
			}
		}

		public static Entity GetUserEntity(this Entity character)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: 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)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (character.TryGetComponent<PlayerCharacter>(out PlayerCharacter componentData))
			{
				return componentData.UserEntity;
			}
			return Entity.Null;
		}

		public static User GetUser(this Entity entity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (entity.TryGetComponent<PlayerCharacter>(out PlayerCharacter componentData) && componentData.UserEntity.TryGetComponent<User>(out User componentData2))
			{
				return componentData2;
			}
			if (entity.TryGetComponent<User>(out componentData2))
			{
				return componentData2;
			}
			return User.Empty;
		}

		public static bool HasBuff(this Entity entity, PrefabGUID buffPrefabGuid)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			ServerGameManager serverGameManager = ServerGameManager;
			return ((ServerGameManager)(ref serverGameManager)).HasBuff(entity, ((PrefabGUID)(ref buffPrefabGuid)).ToIdentifier());
		}

		public static void Destroy(this Entity entity)
		{
			//IL_0000: 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)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			if (entity.Exists())
			{
				DestroyUtility.Destroy(EntityManager, entity, (DestroyDebugReason)0, (string)null, 0);
			}
		}

		public static void SetPosition(this Entity entity, float3 position)
		{
			//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)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			if (entity.Has<AggroConsumer>())
			{
				entity.With<AggroConsumer>((WithRefHandler<AggroConsumer>)delegate(ref AggroConsumer aggroConsumer)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					aggroConsumer.PreCombatPosition = position;
				});
			}
			if (entity.Has<SpawnTransform>())
			{
				entity.With<SpawnTransform>((WithRefHandler<SpawnTransform>)delegate(ref SpawnTransform spawnTransform)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					spawnTransform.Position = position;
				});
			}
			if (entity.Has<Height>())
			{
				entity.With<Height>((WithRefHandler<Height>)delegate(ref Height height)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					height.LastPosition = position;
				});
			}
			if (entity.Has<LocalTransform>())
			{
				entity.With<LocalTransform>((WithRefHandler<LocalTransform>)delegate(ref LocalTransform localTransform)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					localTransform.Position = position;
				});
			}
			if (entity.Has<Translation>())
			{
				entity.With<Translation>((WithRefHandler<Translation>)delegate(ref Translation translation)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					translation.Value = position;
				});
			}
			if (entity.Has<LastTranslation>())
			{
				entity.With<LastTranslation>((WithRefHandler<LastTranslation>)delegate(ref LastTranslation lastTranslation)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					lastTranslation.Value = position;
				});
			}
		}

		public static void SetFaction(this Entity entity, PrefabGUID factionPrefabGUID)
		{
			//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)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if (entity.Has<FactionReference>())
			{
				entity.With<FactionReference>((WithRefHandler<FactionReference>)delegate(ref FactionReference factionReference)
				{
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					factionReference.FactionGuid._Value = factionPrefabGUID;
				});
			}
		}

		public static float3 GetPosition(this Entity entity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: 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)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (entity.TryGetComponent<Translation>(out Translation componentData))
			{
				return componentData.Value;
			}
			return float3.zero;
		}

		public static void Start(this IEnumerator routine)
		{
			Core.StartCoroutine(routine);
		}

		public static void LogEntity(this Entity entity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			EntityManager entityManager = EntityManager;
			World world = ((EntityManager)(ref entityManager)).World;
			StringBuilder val = new StringBuilder();
			bool flag = default(bool);
			try
			{
				EntityDebuggingUtility.DumpEntity(world, entity, true, val);
				ManualLogSource log = Core.Log;
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(13, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Entity Dump:\n");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)val).ToString());
				}
				log.LogInfo(val2);
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = Core.Log;
				BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(22, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Error dumping entity: ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(ex.Message);
				}
				log2.LogWarning(val3);
			}
		}

		public static NativeAccessor<Entity> ToEntityArrayAccessor(this EntityQuery entityQuery, Allocator allocator = 2)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: 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 new NativeAccessor<Entity>(((EntityQuery)(ref entityQuery)).ToEntityArray(AllocatorHandle.op_Implicit(allocator)));
		}

		public static NativeAccessor<T> ToComponentDataArrayAccessor<T>(this EntityQuery entityQuery, Allocator allocator = 2) where T : unmanaged
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: 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 new NativeAccessor<T>(((EntityQuery)(ref entityQuery)).ToComponentDataArray<T>(AllocatorHandle.op_Implicit(allocator)));
		}

		public static EntityQuery BuildEntityQuery(this EntityManager entityManager, ComponentType[] allTypes, ComponentType[] anyTypes = null, ComponentType[] noneTypes = null, EntityQueryOptions? options = null)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: 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_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: 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 (allTypes == null || allTypes.Length == 0)
			{
				throw new ArgumentException("AllTypes must contain at least one component!", "allTypes");
			}
			EntityQueryBuilder val = default(EntityQueryBuilder);
			((EntityQueryBuilder)(ref val))..ctor(AllocatorHandle.op_Implicit((Allocator)2));
			ComponentType[] array = allTypes;
			foreach (ComponentType val2 in array)
			{
				((EntityQueryBuilder)(ref val)).AddAll(val2);
			}
			if (anyTypes != null)
			{
				array = anyTypes;
				foreach (ComponentType val3 in array)
				{
					((EntityQueryBuilder)(ref val)).AddAny(val3);
				}
			}
			if (noneTypes != null)
			{
				array = noneTypes;
				foreach (ComponentType val4 in array)
				{
					((EntityQueryBuilder)(ref val)).AddNone(val4);
				}
			}
			if (options.HasValue)
			{
				((EntityQueryBuilder)(ref val)).WithOptions(options.Value);
			}
			return ((EntityManager)(ref entityManager)).CreateEntityQuery(ref val);
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "io.zfolmt.Penumbra";

		public const string PLUGIN_NAME = "Penumbra";

		public const string PLUGIN_VERSION = "1.1.5";
	}
}
namespace Penumbra.Services
{
	internal class LocalizationService
	{
		private struct Code
		{
			public string Key { get; set; }

			public string Value { get; set; }

			public string Description { get; set; }
		}

		private struct Node
		{
			public string Guid { get; set; }

			public string Text { get; set; }
		}

		private struct Word
		{
			public string Original { get; set; }

			public string Translation { get; set; }
		}

		private struct LocalizationFile
		{
			public Code[] Codes { get; set; }

			public Node[] Nodes { get; set; }

			public Word[] Words { get; set; }
		}

		private static readonly Dictionary<int, string> _guidHashesToGuidStrings = new Dictionary<int, string>();

		private static readonly Dictionary<string, string> _guidStringsToLocalizedNames = new Dictionary<string, string>();

		private static readonly Dictionary<PrefabGUID, string> _prefabGuidNames = new Dictionary<PrefabGUID, string>();

		public static IReadOnlyDictionary<PrefabGUID, string> PrefabGuidNames => _prefabGuidNames;

		public LocalizationService()
		{
			InitializeLocalizations();
			InitializePrefabGuidNames();
		}

		private static void InitializeLocalizations()
		{
			LoadGuidStringsToLocalizedNames();
		}

		private static void InitializePrefabGuidNames()
		{
			//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)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			NativeParallelHashMap<PrefabGUID, ConvertedAssetData> prefabDataLookup = Core.PrefabCollectionSystem._PrefabDataLookup;
			NativeArray<PrefabGUID> keyArray = prefabDataLookup.GetKeyArray(AllocatorHandle.op_Implicit((Allocator)2));
			NativeArray<ConvertedAssetData> valueArray = prefabDataLookup.GetValueArray(AllocatorHandle.op_Implicit((Allocator)2));
			try
			{
				for (int i = 0; i < keyArray.Length; i++)
				{
					PrefabGUID key = keyArray[i];
					ConvertedAssetData val = valueArray[i];
					_prefabGuidNames[key] = ((FixedString128Bytes)(ref val.AssetName)).Value;
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Core.Log;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(33, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Error initializing prefab names: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
				}
				log.LogWarning(val2);
			}
			finally
			{
				keyArray.Dispose();
				valueArray.Dispose();
			}
		}

		private static void LoadGuidStringsToLocalizedNames()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			string text = "Penumbra.Resources.Localization.English.json";
			Stream? manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(text);
			bool flag = default(bool);
			if (manifestResourceStream == null)
			{
				ManualLogSource logInstance = Plugin.LogInstance;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(41, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[Localization] Failed to load resource - ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
				}
				logInstance.LogError(val);
			}
			using StreamReader streamReader = new StreamReader(manifestResourceStream);
			string text2 = streamReader.ReadToEnd();
			if (string.IsNullOrWhiteSpace(text2))
			{
				ManualLogSource logInstance2 = Plugin.LogInstance;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(31, 0, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[Localization] No JSON content!");
				}
				logInstance2.LogError(val);
			}
			LocalizationFile localizationFile = JsonSerializer.Deserialize<LocalizationFile>(text2, new JsonSerializerOptions
			{
				PropertyNameCaseInsensitive = true
			});
			if (localizationFile.Nodes == null)
			{
				ManualLogSource logInstance3 = Plugin.LogInstance;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(58, 0, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[Localization] Deserialized file is null or missing Nodes!");
				}
				logInstance3.LogError(val);
			}
			localizationFile.Nodes.ToDictionary((Node x) => x.Guid, (Node x) => x.Text).ForEach(delegate(KeyValuePair<string, string> kvp)
			{
				_guidStringsToLocalizedNames[kvp.Key] = kvp.Value;
			});
		}

		public static string GetAssetGuidString(PrefabGUID prefabGUID)
		{
			if (_guidHashesToGuidStrings.TryGetValue(((PrefabGUID)(ref prefabGUID)).GuidHash, out var value))
			{
				return value;
			}
			return string.Empty;
		}

		public static string GetGuidString(PrefabGUID prefabGuid)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			if (PrefabNames.LocalizedNameKeys.TryGetValue(prefabGuid, out var value))
			{
				return value;
			}
			return string.Empty;
		}

		public static string GetNameFromGuidString(string guidString)
		{
			if (_guidStringsToLocalizedNames.TryGetValue(guidString, out var value))
			{
				return value;
			}
			return string.Empty;
		}

		public static string GetNameFromPrefabGuid(PrefabGUID prefabGuid)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return GetNameFromGuidString(GetGuidString(prefabGuid));
		}
	}
	internal class MerchantService
	{
		public class MerchantWares
		{
			public string Name;

			public List<PrefabGUID> OutputItems;

			public List<int> OutputAmounts;

			public List<PrefabGUID> InputItems;

			public List<int> InputAmounts;

			public List<int> StockAmounts;

			public int RestockInterval;

			public DateTime NextRestockTime = DateTime.MaxValue;

			public int MerchantIndex;

			public bool Roam;

			public PrefabGUID TraderPrefab;

			public float3 Position;
		}

		private const float TIME_CONSTANT = 60f;

		private const float SPAWN_DELAY = 0.25f;

		private const float ROUTINE_DELAY = 15f;

		private static readonly WaitForSeconds _spawnDelay = new WaitForSeconds(0.25f);

		private static readonly WaitForSeconds _routineDelay = new WaitForSeconds(15f);

		private static readonly PrefabGUID _infiniteInvulnerabilityBuff = PrefabGUIDs.InfiniteInvulnerabilityBuff;

		private static readonly PrefabGUID _buffResistanceUberMob = PrefabGUIDs.BuffResistance_UberMob_IgniteResistant;

		private static readonly PrefabGUID _ignoredFaction = PrefabGUIDs.Faction_Ignored;

		private static readonly ComponentType[] _merchantComponents = (ComponentType[])(object)new ComponentType[2]
		{
			ComponentType.ReadOnly(Il2CppType.Of<Trader>()),
			ComponentType.ReadOnly(Il2CppType.Of<Immortal>())
		};

		private static readonly ComponentType[] _globalPatrolComponents = (ComponentType[])(object)new ComponentType[3]
		{
			ComponentType.ReadOnly(Il2CppType.Of<GlobalPatrolState>()),
			ComponentType.ReadOnly(Il2CppType.Of<MovePatrolState>()),
			ComponentType.ReadOnly(Il2CppType.Of<VBloodUnitSpawnSource>())
		};

		private static EntityQuery _merchantQuery;

		private static readonly ConcurrentDictionary<Entity, MerchantWares> _activeMerchants = new ConcurrentDictionary<Entity, MerchantWares>();

		private static readonly List<MerchantWares> _merchantWares = new List<MerchantWares>();

		private static EntityManager EntityManager => Core.EntityManager;

		private static ServerGameManager ServerGameManager => Core.ServerGameManager;

		private static EntityTypeHandle EntityTypeHandle
		{
			get
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0005: 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)
				EntityManager entityManager = EntityManager;
				return ((EntityManager)(ref entityManager)).GetEntityTypeHandle();
			}
		}

		private static EntityStorageInfoLookup EntityStorageInfoLookup
		{
			get
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0005: 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)
				EntityManager entityManager = EntityManager;
				return ((EntityManager)(ref entityManager)).GetEntityStorageInfoLookup();
			}
		}

		private static ComponentTypeHandle<Immortal> ImmortalHandle
		{
			get
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				EntityManager entityManager = EntityManager;
				return ((EntityManager)(ref entityManager)).GetComponentTypeHandle<Immortal>(true);
			}
		}

		public static IReadOnlyDictionary<Entity, MerchantWares> ActiveMerchants => _activeMerchants;

		public static MerchantWares GetMerchantWares(int index)
		{
			return _merchantWares[index];
		}

		public MerchantService()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			_merchantQuery = EntityManager.BuildEntityQuery(_merchantComponents, null, null, (EntityQueryOptions)2);
			try
			{
				PopulateMerchantWares();
				GetActiveMerchants();
				AutoSpawnMerchants();
				RestockRoutine().Start();
			}
			catch (Exception ex)
			{
				Core.Log.LogError((object)ex);
			}
		}

		private static IEnumerator RestockRoutine()
		{
			bool flag = default(bool);
			while (true)
			{
				DateTime now = DateTime.UtcNow;
				foreach (KeyValuePair<Entity, MerchantWares> activeMerchant in ActiveMerchants)
				{
					try
					{
						Entity key = activeMerchant.Key;
						MerchantWares value = activeMerchant.Value;
						if (!key.Exists())
						{
							_activeMerchants.TryRemove(key, out var _);
							continue;
						}
						if (value.NextRestockTime.Equals(DateTime.MaxValue))
						{
							SyncNextRestock(key, value);
						}
						else if (now >= value.NextRestockTime)
						{
							UpdateMerchantStock(key, value, now);
						}
						goto IL_00fd;
					}
					catch (Exception ex)
					{
						ManualLogSource log = Core.Log;
						BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(28, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("RestockMerchantsRoutine() - ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
						}
						log.LogWarning(val);
						goto IL_00fd;
					}
					IL_00fd:
					yield return null;
				}
				yield return _routineDelay;
			}
		}

		private static void PopulateMerchantWares()
		{
			//IL_0071: 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_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			_ = DateTime.UtcNow;
			foreach (Plugin.MerchantConfig merchant in Plugin.Merchants)
			{
				MerchantWares merchantWares = new MerchantWares();
				merchantWares.Name = merchant.Name;
				MerchantWares merchantWares2 = merchantWares;
				List<PrefabGUID> list = new List<PrefabGUID>();
				foreach (PrefabGUID item3 in ((IEnumerable<string>)merchant.OutputItems).Select((Func<string, PrefabGUID>)((string id) => new PrefabGUID(int.Parse(id)))))
				{
					list.Add(item3);
				}
				merchantWares2.OutputItems = list;
				MerchantWares merchantWares3 = merchantWares;
				List<int> list2 = new List<int>();
				int[] outputAmounts = merchant.OutputAmounts;
				foreach (int item in outputAmounts)
				{
					list2.Add(item);
				}
				merchantWares3.OutputAmounts = list2;
				MerchantWares merchantWares4 = merchantWares;
				List<PrefabGUID> list3 = new List<PrefabGUID>();
				foreach (PrefabGUID item4 in ((IEnumerable<string>)merchant.InputItems).Select((Func<string, PrefabGUID>)((string id) => new PrefabGUID(int.Parse(id)))))
				{
					list3.Add(item4);
				}
				merchantWares4.InputItems = list3;
				MerchantWares merchantWares5 = merchantWares;
				List<int> list4 = new List<int>();
				outputAmounts = merchant.InputAmounts;
				foreach (int item in outputAmounts)
				{
					list4.Add(item);
				}
				merchantWares5.InputAmounts = list4;
				MerchantWares merchantWares6 = merchantWares;
				List<int> list5 = new List<int>();
				outputAmounts = merchant.StockAmounts;
				foreach (int item in outputAmounts)
				{
					list5.Add(item);
				}
				merchantWares6.StockAmounts = list5;
				merchantWares.RestockInterval = merchant.RestockTime;
				merchantWares.MerchantIndex = Plugin.Merchants.IndexOf(merchant);
				merchantWares.Roam = merchant.Roam;
				merchantWares.TraderPrefab = new PrefabGUID(merchant.TraderPrefab);
				merchantWares.Position = ParseFloat3FromString(merchant.Position);
				MerchantWares item2 = merchantWares;
				_merchantWares.Add(item2);
			}
		}

		public static void SpawnMerchant(PrefabGUID traderPrefabGuid, float3 aimPosition, MerchantWares wares)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			ServerGameManager serverGameManager = ServerGameManager;
			Entity merchant = ((ServerGameManager)(ref serverGameManager)).InstantiateEntityImmediate(Entity.Null, traderPrefabGuid);
			ApplyOrRefreshModifications(merchant, wares);
			ModifyMerchant(merchant, aimPosition, wares).Start();
			Plugin.Instance.UpdateMerchantDefinition(wares.MerchantIndex, ((PrefabGUID)(ref traderPrefabGuid)).GuidHash, aimPosition);
		}

		private static void ApplyOrRefreshModifications(Entity merchant, MerchantWares wares)
		{
			//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)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			if (merchant.Exists())
			{
				merchant.AddWith<EntityOwner>((VExtensions.WithRefHandler<EntityOwner>)delegate(ref EntityOwner entityOwner)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					entityOwner.Owner = merchant;
				});
				merchant.AddWith<Buffable>((VExtensions.WithRefHandler<Buffable>)delegate(ref Buffable buffable)
				{
					buffable.KnockbackResistanceIndex._Value = 11;
				});
				merchant.AddWith<BuffResistances>((VExtensions.WithRefHandler<BuffResistances>)delegate(ref BuffResistances buffResistances)
				{
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					buffResistances.InitialSettingGuid = _buffResistanceUberMob;
				});
				merchant.AddWith<Immortal>((VExtensions.WithRefHandler<Immortal>)delegate(ref Immortal immortal)
				{
					immortal.IsImmortal = true;
				});
				merchant.AddWith<NameableInteractable>((VExtensions.WithRefHandler<NameableInteractable>)delegate(ref NameableInteractable nameableInteractable)
				{
					//IL_000c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0011: Unknown result type (might be due to invalid IL or missing references)
					nameableInteractable.Name = new FixedString64Bytes(wares.Name);
				});
				merchant.With<DynamicCollision>((VExtensions.WithRefHandler<DynamicCollision>)delegate(ref DynamicCollision dynamicCollision)
				{
					dynamicCollision.Immobile = true;
				});
				MakeImperviousAndIgnored(merchant, wares.Roam);
			}
		}

		private static void MakeImperviousAndIgnored(Entity merchant, bool roam = false)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_0009: 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)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: 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_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			ServerGameManager serverGameManager = ServerGameManager;
			Entity entity = ((ServerGameManager)(ref serverGameManager)).InstantiateBuffEntityImmediate(merchant, merchant, _infiniteInvulnerabilityBuff, (OnSpawnedDelegate)null, 1);
			if (!entity.Exists())
			{
				return;
			}
			if (!roam)
			{
				entity.AddWith<ModifyMovementSpeedBuff>((VExtensions.WithRefHandler<ModifyMovementSpeedBuff>)delegate(ref ModifyMovementSpeedBuff modifyMovementSpeed)
				{
					modifyMovementSpeed.MoveSpeed = 0f;
					modifyMovementSpeed.MultiplyAdd = false;
				});
			}
			entity.AddWith<Script_Buff_ModifyFaction_DataServer>((VExtensions.WithRefHandler<Script_Buff_ModifyFaction_DataServer>)delegate(ref Script_Buff_ModifyFaction_DataServer modifyFaction)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				modifyFaction.Faction = _ignoredFaction;
			});
			entity.Add<ScriptSpawn>();
		}

		private static IEnumerator ModifyMerchant(Entity merchant, float3 aimPosition, MerchantWares wares)
		{
			//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)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			yield return _spawnDelay;
			merchant.SetPosition(aimPosition);
			merchant.With<UnitStats>((VExtensions.WithRefHandler<UnitStats>)delegate(ref UnitStats unitStats)
			{
				unitStats.DamageReduction._Value = 100f;
				unitStats.PhysicalResistance._Value = 100f;
				unitStats.SpellResistance._Value = 100f;
				unitStats.HealthRecovery._Value = 1f;
				unitStats.FireResistance._Value = wares.MerchantIndex;
			});
			merchant.AddWith<Immortal>((VExtensions.WithRefHandler<Immortal>)delegate(ref Immortal immortal)
			{
				immortal.IsImmortal = true;
			});
			merchant.With<DynamicCollision>((VExtensions.WithRefHandler<DynamicCollision>)delegate(ref DynamicCollision dynamicCollision)
			{
				dynamicCollision.Immobile = true;
			});
			_activeMerchants.TryAdd(merchant, wares);
			DateTime utcNow = DateTime.UtcNow;
			UpdateMerchantStock(merchant, wares, utcNow);
		}

		private static void UpdateMerchantStock(Entity merchant, MerchantWares merchantWares, DateTime now)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			float restockTime = (float)merchantWares.RestockInterval * 60f;
			merchantWares.NextRestockTime = now.AddMinutes(merchantWares.RestockInterval);
			DynamicBuffer<TradeOutput> val = merchant.ReadBuffer<TradeOutput>();
			DynamicBuffer<TraderEntry> val2 = merchant.ReadBuffer<TraderEntry>();
			DynamicBuffer<TradeCost> val3 = merchant.ReadBuffer<TradeCost>();
			val.Clear();
			val2.Clear();
			val3.Clear();
			for (int i = 0; i < merchantWares.OutputItems.Count; i++)
			{
				val.Add(new TradeOutput
				{
					Amount = (ushort)merchantWares.OutputAmounts[i],
					Item = merchantWares.OutputItems[i]
				});
				val3.Add(new TradeCost
				{
					Amount = (ushort)merchantWares.InputAmounts[i],
					Item = merchantWares.InputItems[i]
				});
				val2.Add(new TraderEntry
				{
					RechargeInterval = restockTime,
					CostCount = 1,
					CostStartIndex = (byte)i,
					FullRechargeTime = restockTime,
					OutputCount = 1,
					OutputStartIndex = (byte)i,
					StockAmount = (ushort)merchantWares.StockAmounts[i]
				});
			}
			merchant.AddWith<Trader>((VExtensions.WithRefHandler<Trader>)delegate(ref Trader trader)
			{
				trader.RestockTime = restockTime;
				trader.PrevRestockTime = Core.ServerTime;
				trader.NextRestockTime = Core.ServerTime + (double)restockTime;
			});
		}

		private static void SyncNextRestock(Entity merchant, MerchantWares merchantWares)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			Trader val = merchant.Read<Trader>();
			double serverTime = Core.ServerTime;
			float restockTime = (float)merchantWares.RestockInterval * 60f;
			double num = val.NextRestockTime - val.PrevRestockTime;
			if (!val.RestockTime.Equals(restockTime))
			{
				merchant.With<Trader>((VExtensions.WithRefHandler<Trader>)delegate(ref Trader trader)
				{
					trader.RestockTime = restockTime;
				});
			}
			if (serverTime > val.NextRestockTime || num > (double)restockTime)
			{
				UpdateMerchantStock(merchant, merchantWares, DateTime.UtcNow);
			}
		}

		private static void GetActiveMerchants()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			NativeArray<ArchetypeChunk> val = ((EntityQuery)(ref _merchantQuery)).CreateArchetypeChunkArray(AllocatorHandle.op_Implicit((Allocator)2));
			EntityStorageInfoLookup entityStorageInfoLookup = EntityStorageInfoLookup;
			int num = 0;
			try
			{
				Enumerator<ArchetypeChunk> enumerator = val.GetEnumerator();
				while (enumerator.MoveNext())
				{
					ArchetypeChunk current = enumerator.Current;
					NativeArray<Entity> nativeArray = ((ArchetypeChunk)(ref current)).GetNativeArray(EntityTypeHandle);
					((ArchetypeChunk)(ref current)).GetNativeArray<Immortal>(ImmortalHandle);
					for (int i = 0; i < ((ArchetypeChunk)(ref current)).Count; i++)
					{
						Entity val2 = nativeArray[i];
						if (((EntityStorageInfoLookup)(ref entityStorageInfoLookup)).Exists(val2))
						{
							int merchantIndex = GetMerchantIndex(val2);
							if (merchantIndex >= 0 && merchantIndex < _merchantWares.Count)
							{
								MerchantWares merchantWares = GetMerchantWares(merchantIndex);
								ApplyOrRefreshModifications(val2, merchantWares);
								_activeMerchants.TryAdd(val2, merchantWares);
								num++;
							}
						}
					}
				}
			}
			finally
			{
				val.Dispose();
				ManualLogSource log = Core.Log;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(44, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Tracking ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<int>(num);
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" Penumbra merchants found in world!");
				}
				log.LogWarning(val3);
			}
		}

		private static int GetMerchantIndex(Entity merchant)
		{
			//IL_0000: 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)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (merchant.TryGetComponent<UnitStats>(out UnitStats componentData))
			{
				return componentData.FireResistance._Value;
			}
			return -1;
		}

		private static float3 ParseFloat3FromString(string configString)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(configString))
			{
				return float3.zero;
			}
			string[] array = configString.Split(',');
			if (array.Length != 3)
			{
				throw new FormatException("Invalid float3 string format. Expected format: 'x,y,z'.");
			}
			return new float3(float.Parse(array[0], CultureInfo.InvariantCulture), float.Parse(array[1], CultureInfo.InvariantCulture), float.Parse(array[2], CultureInfo.InvariantCulture));
		}

		private static void AutoSpawnMerchants()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_0111: 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_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			bool flag2 = default(bool);
			for (int i = 0; i < _merchantWares.Count; i++)
			{
				MerchantWares merchantWares = _merchantWares[i];
				string name = merchantWares.Name;
				bool flag = false;
				if (((PrefabGUID)(ref merchantWares.TraderPrefab)).IsEmpty() || ((float3)(ref merchantWares.Position)).Equals(float3.zero))
				{
					continue;
				}
				foreach (KeyValuePair<Entity, MerchantWares> activeMerchant in _activeMerchants)
				{
					if (activeMerchant.Key.TryGetComponent<NameableInteractable>(out NameableInteractable componentData) && name.Equals(((FixedString64Bytes)(ref componentData.Name)).Value))
					{
						flag = true;
					}
				}
				if (!flag)
				{
					ManualLogSource log = Core.Log;
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(49, 3, ref flag2);
					if (flag2)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[MerchantService] Auto-spawning merchant ");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("#");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(i + 1);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(merchantWares.TraderPrefab.GetPrefabName());
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") at ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float3>(merchantWares.Position);
					}
					log.LogInfo(val);
					SpawnMerchant(merchantWares.TraderPrefab, merchantWares.Position, merchantWares);
				}
			}
		}
	}
	internal static class PlayerService
	{
		public struct PlayerInfo
		{
			public User User { get; set; }

			public Entity UserEntity { get; set; }

			public Entity CharEntity { get; set; }

			public PlayerInfo(Entity userEntity = default(Entity), Entity charEntity = default(Entity), User user = default(User))
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: 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)
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				User = user;
				UserEntity = userEntity;
				CharEntity = charEntity;
			}
		}

		private static readonly bool _tokens;

		private static readonly bool _daily;

		private static readonly ConcurrentDictionary<ulong, PlayerInfo> _steamIdPlayerInfoCache;

		private static EntityManager EntityManager => Core.EntityManager;

		public static IReadOnlyDictionary<ulong, PlayerInfo> SteamIdPlayerInfoCache => _steamIdPlayerInfoCache;

		static PlayerService()
		{
			//IL_0035: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			_tokens = Plugin._tokensConfig.TokenSystem;
			_daily = Plugin._tokensConfig.DailyLogin;
			_steamIdPlayerInfoCache = new ConcurrentDictionary<ulong, PlayerInfo>();
			ComponentType[] allTypes = (ComponentType[])(object)new ComponentType[1] { ComponentType.ReadOnly(Il2CppType.Of<User>()) };
			BuildPlayerInfoCache(EntityManager.BuildEntityQuery(allTypes, null, null, (EntityQueryOptions)2));
		}

		private static void BuildPlayerInfoCache(EntityQuery userQuery)
		{
			//IL_0003: 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)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			NativeArray<Entity> val = ((EntityQuery)(ref userQuery)).ToEntityArray(AllocatorHandle.op_Implicit((Allocator)2));
			try
			{
				Enumerator<Entity> enumerator = val.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Entity current = enumerator.Current;
					if (current.Exists())
					{
						User user = current.GetUser();
						Entity entityOnServer = ((NetworkedEntity)(ref user.LocalCharacter)).GetEntityOnServer();
						ulong platformId = user.PlatformId;
						_ = ((FixedString64Bytes)(ref user.CharacterName)).Value;
						_steamIdPlayerInfoCache[platformId] = new PlayerInfo(current, entityOnServer, user);
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Core.Log;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(41, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[PlayerService] BuildPlayerInfoCache() - ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex);
				}
				log.LogWarning(val2);
			}
			finally
			{
				val.Dispose();
			}
		}

		public static void HandleConnection(ulong steamId, PlayerInfo player)
		{
			//IL_0026: 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_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			if (!_tokens)
			{
				return;
			}
			if (!TokenService.PlayerTokens.TryGetValue(steamId, out var value))
			{
				steamId.CreateTokens();
				if (_daily)
				{
					TokenService.TryGiveDaily(player.User, player.CharEntity);
				}
				return;
			}
			value.TimeData = new TokenService.TimeBlob(DateTime.UtcNow, value.TimeData.LoginTime);
			steamId.UpdateAndSaveTokens(value);
			if (_daily && TokenService.IsEligibleForDaily(value))
			{
				TokenService.TryGiveDaily(player.User, player.CharEntity);
				value.TimeData = new TokenService.TimeBlob(value.TimeData.TokenTime, DateTime.UtcNow);
				steamId.UpdateAndSaveTokens(value);
			}
		}

		public static bool TryGetPlayerInfo(this ulong steamId, out PlayerInfo playerInfo)
		{
			if (SteamIdPlayerInfoCache.TryGetValue(steamId, out playerInfo))
			{
				return true;
			}
			return false;
		}
	}
	internal static class TokenService
	{
		[Serializable]
		public struct TimeBlob
		{
			public DateTime TokenTime;

			public DateTime LoginTime;

			public TimeBlob(DateTime tokenTime, DateTime dailyLogin)
			{
				TokenTime = tokenTime;
				LoginTime = dailyLogin;
			}
		}

		[Serializable]
		public struct TokenBlob
		{
			public int Tokens;

			public TimeBlob TimeData;

			public TokenBlob(int tokens, TimeBlob timeBlob)
			{
				Tokens = tokens;
				TimeData = timeBlob;
			}
		}

		private static readonly bool _tokens = Plugin._tokensConfig.TokenSystem;

		private static readonly int _tokenRate = Plugin._tokensConfig.TokenRate;

		private static readonly int _tokenRatio = Plugin._tokensConfig.TokenRatio;

		private static readonly int _dailyQuantity = Plugin._tokensConfig.DailyQuantity;

		private static readonly PrefabGUID _tokenItem = Plugin._tokensConfig.TokenItem;

		private static readonly PrefabGUID _dailyItem = Plugin._tokensConfig.DailyItem;

		private static readonly WaitForSeconds _delay = new WaitForSeconds((float)Plugin._tokensConfig.UpdateInterval);

		private static readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions
		{
			WriteIndented = true,
			IncludeFields = true
		};

		private static bool _initialized = false;

		private static ConcurrentDictionary<ulong, TokenBlob> _playerTokens = new ConcurrentDictionary<ulong, TokenBlob>();

		private static EntityManager EntityManager => Core.EntityManager;

		private static ServerGameManager ServerGameManager => Core.ServerGameManager;

		public static IReadOnlyDictionary<ulong, TokenBlob> PlayerTokens => _playerTokens;

		public static void Initialize()
		{
			if (!_initialized)
			{
				_initialized = true;
				TokensRoutine().Start();
			}
		}

		private static IEnumerator TokensRoutine()
		{
			while (true)
			{
				Dictionary<ulong, TokenBlob> updated = new Dictionary<ulong, TokenBlob>();
				foreach (KeyValuePair<ulong, PlayerService.PlayerInfo> item in PlayerService.SteamIdPlayerInfoCache)
				{
					User user = item.Value.User;
					if (!user.IsConnected)
					{
						continue;
					}
					ulong platformId = user.PlatformId;
					if (!PlayerTokens.TryGetValue(platformId, out var value))
					{
						platformId.CreateTokens();
						continue;
					}
					if (_tokens)
					{
						value = AccumulateTime(value);
						updated[platformId] = value;
					}
					yield return null;
				}
				foreach (KeyValuePair<ulong, TokenBlob> item2 in updated)
				{
					item2.Key.UpdateTokens(item2.Value);
				}
				SaveTokens();
				yield return _delay;
			}
		}

		public static TokenBlob AccumulateTime(TokenBlob tokenData)
		{
			int num = (DateTime.UtcNow - tokenData.TimeData.TokenTime).Minutes * _tokenRate;
			return new TokenBlob(tokenData.Tokens + num, new TimeBlob
			{
				TokenTime = DateTime.UtcNow,
				LoginTime = tokenData.TimeData.LoginTime
			});
		}

		public static bool IsEligibleForDaily(TokenBlob tokenData)
		{
			return DateTime.UtcNow >= tokenData.TimeData.LoginTime.AddDays(1.0);
		}

		public static TimeSpan TimeUntilNextDaily(TokenBlob tokenData)
		{
			return tokenData.TimeData.LoginTime.AddDays(1.0) - DateTime.UtcNow;
		}

		public static void TryGiveDaily(User user, Entity characterEntity)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			if (characterEntity.Exists())
			{
				string localizedName = _dailyItem.GetLocalizedName();
				string text = $"You've received <color=#00FFFF>{localizedName}</color>x<color=white>{_dailyQuantity}</color> for logging in today!";
				ServerGameManager serverGameManager = ServerGameManager;
				if (AddItemResponse.op_Implicit(((ServerGameManager)(ref serverGameManager)).TryAddInventoryItem(characterEntity, _dailyItem, _dailyQuantity)))
				{
					FixedString512Bytes val = default(FixedString512Bytes);
					((FixedString512Bytes)(ref val))..ctor(text);
					ServerChatUtils.SendSystemMessageToClient(EntityManager, user, ref val);
				}
				else
				{
					FixedString512Bytes val2 = default(FixedString512Bytes);
					((FixedString512Bytes)(ref val2))..ctor(text + " It dropped on the ground because your inventory was full.");
					InventoryUtilitiesServer.CreateDropItem(EntityManager, characterEntity, _dailyItem, _dailyQuantity, default(Entity));
					ServerChatUtils.SendSystemMessageToClient(EntityManager, user, ref val2);
				}
			}
		}

		public static voi