Decompiled source of Lethal Questing v1.3.1

LethalQuesting.dll

Decompiled 3 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CSync.Extensions;
using CSync.Lib;
using GameNetcodeStuff;
using HarmonyLib;
using LethalNetworkAPI;
using LethalQuesting.Core;
using LethalQuesting.Managers;
using LethalQuesting.Models;
using LethalQuesting.UI;
using LethalQuesting.Utils;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LethalQuesting")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LethalQuesting")]
[assembly: AssemblyTitle("LethalQuesting")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace LethalQuesting
{
	public class NetworkHandler
	{
		public static LNetworkVariable<List<QuestData>> TodaysQuestsData = LNetworkVariable<List<QuestData>>.Create("TodaysQuestsData", (List<QuestData>)null, (LNetworkVariableWritePerms)0, (Action<List<QuestData>, List<QuestData>>)null);

		public static LNetworkMessage<ulong> ItemDroppedMessage = LNetworkMessage<ulong>.Create("ItemDropped", (Action<ulong, ulong>)null, (Action<ulong>)null, (Action<ulong, ulong>)null);

		public static void Initialize()
		{
			TodaysQuestsData.OnValueChanged += delegate(List<QuestData> oldVal, List<QuestData> newVal)
			{
				UpdateQuests.UpdateTheQuests(newVal);
			};
			ItemDroppedMessage.OnServerReceived += delegate(ulong objId, ulong senderId)
			{
				if (NetworkManager.Singleton.IsServer)
				{
					ScrapManager.CheckScrapCollection(objId);
				}
			};
		}
	}
}
namespace LethalQuesting.Utils
{
	public static class EnemyNameHelper
	{
		private static readonly Dictionary<string, string> EnemyCleanNames = new Dictionary<string, string>
		{
			{ "Flowerman", "Bracken" },
			{ "Crawler", "Thumper" },
			{ "Spring", "Coil-Head" },
			{ "MouthDog", "Eyeless Dog" },
			{ "ForestGiant", "Forest Giant" },
			{ "HoardingBug", "Hoarding Bug" },
			{ "Jester", "Jester" },
			{ "Centipede", "Snare Flea" },
			{ "Puffer", "Spore Lizard" },
			{ "Bunker Spider", "Bunker Spider" },
			{ "Nutcracker", "Nutcracker" },
			{ "Masked", "Masked" },
			{ "Girl", "Ghost Girl" },
			{ "Blob", "Hygrodere" },
			{ "RadMech", "Old Bird" }
		};

		public static string GetCleanName(string internalName)
		{
			string value;
			return EnemyCleanNames.TryGetValue(internalName, out value) ? value : internalName;
		}
	}
	public class MathUtils
	{
		public static int SimpleBellCurve(float min, float max)
		{
			float num = Random.Range(min, max);
			float num2 = Random.Range(min, max);
			float num3 = Random.Range(min, max);
			return Mathf.RoundToInt((num + num2 + num3) / 3f);
		}

		public static string IncrementStringNumber(string input)
		{
			if (int.TryParse(input, out var result))
			{
				return (result + 1).ToString();
			}
			return input;
		}
	}
}
namespace LethalQuesting.UI
{
	public class QuestUI
	{
		[HarmonyPatch(typeof(QuickMenuManager))]
		public class MenuTogglePatch
		{
			[HarmonyPatch("OpenQuickMenu")]
			[HarmonyPostfix]
			private static void OnMenuOpen()
			{
				Plugin.IsEscMenuOpen = true;
				if ((Object)(object)Plugin.myCustomText != (Object)null && (Object)(object)((TMP_Text)Plugin.myCustomText).transform.parent != (Object)null)
				{
					((Component)((TMP_Text)Plugin.myCustomText).transform.parent).gameObject.SetActive(false);
				}
			}

			[HarmonyPatch("CloseQuickMenu")]
			[HarmonyPostfix]
			private static void OnMenuClose()
			{
				RefreshUILayout();
				Plugin.IsEscMenuOpen = false;
				if ((Object)(object)Plugin.myCustomText != (Object)null && (Object)(object)((TMP_Text)Plugin.myCustomText).transform.parent != (Object)null)
				{
					((Component)((TMP_Text)Plugin.myCustomText).transform.parent).gameObject.SetActive(Plugin.IsUIVisible);
				}
			}
		}

		public static void CreateTextOnHUD()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Expected O, but got Unknown
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Plugin.myCustomText != (Object)null)
			{
				return;
			}
			GameObject val = GameObject.Find("Systems/UI/Canvas");
			if ((Object)(object)val == (Object)null)
			{
				Canvas obj = Object.FindObjectOfType<Canvas>();
				val = ((obj != null) ? ((Component)obj).gameObject : null);
			}
			if (!((Object)(object)val == (Object)null))
			{
				GameObject val2 = new GameObject("QuestLogContainer");
				val2.transform.SetParent(val.transform, false);
				val2.layer = 5;
				GameObject val3 = new GameObject("QuestDebugBG");
				val3.transform.SetParent(val2.transform, false);
				Image val4 = val3.AddComponent<Image>();
				((Graphic)val4).color = new Color(1f, 0f, 0f, 0.3f);
				val3.SetActive(Plugin.ConfigDebugFunctionality.Value);
				GameObject val5 = new GameObject("QuestText");
				val5.transform.SetParent(val2.transform, false);
				Plugin.myCustomText = val5.AddComponent<TextMeshProUGUI>();
				if ((Object)(object)HUDManager.Instance != (Object)null && HUDManager.Instance.controlTipLines.Length != 0)
				{
					((TMP_Text)Plugin.myCustomText).font = ((TMP_Text)HUDManager.Instance.controlTipLines[0]).font;
					((TMP_Text)Plugin.myCustomText).fontSharedMaterial = ((TMP_Text)HUDManager.Instance.controlTipLines[0]).fontSharedMaterial;
				}
				((TMP_Text)Plugin.myCustomText).text = "Press K to toggle quest texts at anytime.";
				((TMP_Text)Plugin.myCustomText).fontSize = Plugin.ConfigUIFontSize.Value;
				((Graphic)Plugin.myCustomText).color = new Color(0.8f, 0.8f, 0.8f);
				((TMP_Text)Plugin.myCustomText).alignment = (TextAlignmentOptions)260;
				RectTransform val6 = val2.AddComponent<RectTransform>();
				Vector2 val7 = default(Vector2);
				((Vector2)(ref val7))..ctor(1f, 1f);
				val6.pivot = val7;
				Vector2 anchorMin = (val6.anchorMax = val7);
				val6.anchorMin = anchorMin;
				val6.anchoredPosition = new Vector2((float)(-Plugin.ConfigUIOffsetX.Value), (float)(-Plugin.ConfigUIOffsetY.Value));
				val6.sizeDelta = new Vector2((float)Plugin.ConfigUIWidth.Value, (float)Plugin.ConfigUIHeight.Value);
				FillParent(val3.GetComponent<RectTransform>());
				FillParent(val5.GetComponent<RectTransform>());
			}
		}

		public static void RefreshUILayout()
		{
			//IL_0088: 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)
			if (!((Object)(object)Plugin.myCustomText == (Object)null) && !((Object)(object)((TMP_Text)Plugin.myCustomText).transform.parent == (Object)null))
			{
				GameObject gameObject = ((Component)((TMP_Text)Plugin.myCustomText).transform.parent).gameObject;
				RectTransform component = gameObject.GetComponent<RectTransform>();
				((TMP_Text)Plugin.myCustomText).fontSize = Plugin.ConfigUIFontSize.Value;
				if ((Object)(object)component != (Object)null)
				{
					component.anchoredPosition = new Vector2((float)(-Plugin.ConfigUIOffsetX.Value), (float)(-Plugin.ConfigUIOffsetY.Value));
					component.sizeDelta = new Vector2((float)Plugin.ConfigUIWidth.Value, (float)Plugin.ConfigUIHeight.Value);
				}
				Transform val = gameObject.transform.Find("QuestDebugBG");
				if ((Object)(object)val != (Object)null)
				{
					((Component)val).gameObject.SetActive(Plugin.IsUIVisible && Plugin.ConfigDebugFunctionality.Value);
				}
			}
		}

		private static void FillParent(RectTransform r)
		{
			//IL_0002: 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_001a: 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)
			r.anchorMin = Vector2.zero;
			r.anchorMax = Vector2.one;
			r.sizeDelta = Vector2.zero;
			r.anchoredPosition = Vector2.zero;
		}

		public static void UpdateQuestLog(string Quests)
		{
			if ((Object)(object)Plugin.myCustomText == (Object)null)
			{
				CreateTextOnHUD();
			}
			((Component)Plugin.myCustomText).gameObject.SetActive(Plugin.IsUIVisible);
			((TMP_Text)Plugin.myCustomText).transform.SetAsLastSibling();
			((TMP_Text)Plugin.myCustomText).text = Quests ?? "";
			if (Plugin.ConfigOutputDebugLogs.Value)
			{
				Plugin.mls.LogInfo((object)"UI updated!");
			}
		}
	}
}
namespace LethalQuesting.Patches
{
	[HarmonyPatch(typeof(TimeOfDay), "Start")]
	public class RegisterHourPatch
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__0_0;

			internal void <Postfix>b__0_0()
			{
				Plugin.LogLivingEnemies();
			}
		}

		private static void Postfix(TimeOfDay __instance)
		{
			//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_0026: Expected O, but got Unknown
			UnityEvent onHourChanged = __instance.onHourChanged;
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				UnityAction val = delegate
				{
					Plugin.LogLivingEnemies();
				};
				<>c.<>9__0_0 = val;
				obj = (object)val;
			}
			onHourChanged.AddListener((UnityAction)obj);
		}
	}
	[HarmonyPatch(typeof(HUDManager), "Update")]
	public static class KeyboardShortcutPatch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			try
			{
				if ((Object)(object)HUDManager.Instance == (Object)null || Plugin.IsEscMenuOpen)
				{
					return;
				}
				PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
				if ((!((Object)(object)localPlayerController != (Object)null) || (!localPlayerController.isTypingChat && !localPlayerController.inTerminalMenu)) && ((ButtonControl)Keyboard.current.kKey).wasPressedThisFrame && (Object)(object)Plugin.myCustomText != (Object)null)
				{
					Plugin.IsUIVisible = !Plugin.IsUIVisible;
					GameObject gameObject = ((Component)((TMP_Text)Plugin.myCustomText).transform.parent).gameObject;
					gameObject.SetActive(Plugin.IsUIVisible);
					Transform val = gameObject.transform.Find("QuestDebugBG");
					if ((Object)(object)val != (Object)null)
					{
						((Component)val).gameObject.SetActive(Plugin.ConfigDebugFunctionality.Value);
					}
					if (Plugin.ConfigOutputDebugLogs.Value)
					{
						Plugin.mls.LogInfo((object)$"UI toggled to: {Plugin.IsUIVisible}");
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.mls.LogError((object)$"Update error: {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager), "Start")]
	public class HUDManagerPatch
	{
		[HarmonyPostfix]
		private static void ShowHUD()
		{
			QuestUI.CreateTextOnHUD();
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	public static class ShipLeavePatch
	{
		[HarmonyPatch("EndOfGame")]
		[HarmonyPostfix]
		private static void SetLobbyText(int bodiesInsured, int connectedPlayersOnServer, int scrapCollected)
		{
			QuestManager.QuestsGeneratedForThisRound = false;
			string quests = "<color=#CCCCCC>Press K to toggle quest texts at anytime.</color>";
			QuestUI.UpdateQuestLog(quests);
		}
	}
	[HarmonyPatch(typeof(VehicleController))]
	public class VehicleQuestPatch
	{
		private static bool _hasScannedThisTrip;

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void ScanItemsInVehicle(VehicleController __instance)
		{
			if (!((NetworkBehaviour)RoundManager.Instance).IsServer)
			{
				return;
			}
			if (__instance.magnetedToShip && __instance.magnetTime >= 1f && !_hasScannedThisTrip)
			{
				_hasScannedThisTrip = true;
				GrabbableObject[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<GrabbableObject>();
				if (componentsInChildren.Length != 0)
				{
					if (Plugin.ConfigOutputDebugLogs.Value)
					{
						Plugin.mls.LogInfo((object)$"[LethalQuesting] Araba gemiye bağlandı. {componentsInChildren.Length} eşya kontrol ediliyor.");
					}
					GrabbableObject[] array = componentsInChildren;
					foreach (GrabbableObject val in array)
					{
						ScrapManager.CheckScrapCollection(((NetworkBehaviour)val).NetworkObjectId);
					}
				}
			}
			if (!__instance.magnetedToShip && _hasScannedThisTrip)
			{
				_hasScannedThisTrip = false;
			}
		}
	}
}
namespace LethalQuesting.Models
{
	public enum QuestType
	{
		None,
		Scrap,
		Kill,
		Survive,
		Betray,
		JumpLimit
	}
	public struct QuestData : INetworkSerializable
	{
		public QuestType Type;

		public string Title;

		public string TargetName;

		public int TargetCount;

		public int CurrentCount;

		public int Reward;

		public bool IsRewardGiven;

		public unsafe void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
		{
			//IL_000b: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: 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_008b: Unknown result type (might be due to invalid IL or missing references)
			((BufferSerializer<QuestType>*)(&serializer))->SerializeValue<QuestType>(ref Type, default(ForEnums));
			serializer.SerializeValue(ref Title, false);
			serializer.SerializeValue(ref TargetName, false);
			((BufferSerializer<int>*)(&serializer))->SerializeValue<int>(ref TargetCount, default(ForPrimitives));
			((BufferSerializer<int>*)(&serializer))->SerializeValue<int>(ref CurrentCount, default(ForPrimitives));
			((BufferSerializer<int>*)(&serializer))->SerializeValue<int>(ref Reward, default(ForPrimitives));
			((BufferSerializer<bool>*)(&serializer))->SerializeValue<bool>(ref IsRewardGiven, default(ForPrimitives));
		}
	}
	public struct ScrapPoolEntry
	{
		public string Name;

		public int TotalCount;

		public int AverageValue;
	}
	public class ScrapData
	{
		public string Name;

		public int Value;

		public ulong NetworkId;

		public bool IsCollected;

		public ScrapData(GrabbableObject obj)
		{
			Name = obj.itemProperties.itemName;
			Value = obj.scrapValue;
			NetworkId = ((NetworkBehaviour)obj).NetworkObjectId;
			IsCollected = false;
		}
	}
}
namespace LethalQuesting.Managers
{
	[HarmonyPatch(typeof(RoundManager))]
	public static class QuestManager
	{
		public static bool QuestsGeneratedForThisRound;

		[HarmonyPatch("SyncScrapValuesClientRpc")]
		[HarmonyPostfix]
		public static void GenerateDailyQuest(NetworkObjectReference[] spawnedScrap, int[] allScrapValue)
		{
			if (!NetworkManager.Singleton.IsServer || QuestsGeneratedForThisRound)
			{
				return;
			}
			NetworkHandler.TodaysQuestsData.Value = new List<QuestData>();
			int num = MathUtils.SimpleBellCurve(0f, Plugin.CustomConfig.ConfigAverageQuestCount.Value * 2f);
			ScrapManager.ScanMapForScraps();
			ScrapManager.PrepareScrapPool();
			if (Plugin.ConfigOutputDebugLogs.Value)
			{
				Plugin.mls.LogInfo((object)$"Crew rolled {num} quests!");
			}
			List<QuestData> list = new List<QuestData>();
			for (int i = 0; i < num; i++)
			{
				QuestData? questData = GenerateScrapQuestFromPool();
				if (questData.HasValue)
				{
					list.Add(questData.Value);
				}
			}
			NetworkHandler.TodaysQuestsData.Value = list;
			QuestsGeneratedForThisRound = true;
		}

		private static QuestData? GenerateScrapQuestFromPool()
		{
			if (ScrapManager.SelectedScrapPool.Count == 0)
			{
				return null;
			}
			ScrapPoolEntry scrapPoolEntry = ScrapManager.SelectedScrapPool[0];
			ScrapManager.SelectedScrapPool.RemoveAt(0);
			int num = Mathf.Max(1, Mathf.RoundToInt((float)scrapPoolEntry.TotalCount * Random.Range(0.3f, 0.8f)));
			QuestData value = default(QuestData);
			value.Type = QuestType.Scrap;
			value.Title = "Priority Retrieval: " + scrapPoolEntry.Name;
			value.TargetName = scrapPoolEntry.Name;
			value.TargetCount = num;
			value.CurrentCount = 0;
			value.Reward = CalculateReward(num, scrapPoolEntry.AverageValue);
			value.IsRewardGiven = false;
			return value;
		}

		private static int CalculateReward(int count, int averageValue)
		{
			return (int)((double)((float)TimeOfDay.Instance.profitQuota * Plugin.CustomConfig.ConfigPercentOfQuota.Value) * ((double)((float)averageValue / 100f) + (double)count * 0.4));
		}
	}
	public class UpdateQuests
	{
		public static void UpdateTheQuests(List<QuestData> questList)
		{
			if (questList == null || questList.Count == 0)
			{
				QuestUI.UpdateQuestLog("No missions today.");
				return;
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < questList.Count; i++)
			{
				QuestData questData = questList[i];
				if (questData.Type != 0)
				{
					string text = ((questData.CurrentCount >= questData.TargetCount) ? "green" : "orange");
					string text2 = "";
					text2 = questData.Type switch
					{
						QuestType.Scrap => $"Collect {questData.TargetName}: {questData.CurrentCount}/{questData.TargetCount}", 
						QuestType.Kill => $"Exterminate {questData.TargetName}: {questData.CurrentCount}/{questData.TargetCount}", 
						_ => $"{questData.Title}: {questData.CurrentCount}/{questData.TargetCount}", 
					};
					stringBuilder.AppendLine("<color=" + text + ">" + text2 + "</color>");
					stringBuilder.AppendLine(string.Format("<color={0}>Reward: ■{1} {2}</color>", text, questData.Reward, (questData.CurrentCount >= questData.TargetCount) ? "(Paid)" : ""));
					stringBuilder.AppendLine();
					if (NetworkManager.Singleton.IsServer && questData.CurrentCount >= questData.TargetCount && !questData.IsRewardGiven)
					{
						GiveReward(i);
					}
				}
			}
			QuestUI.UpdateQuestLog(stringBuilder.ToString());
		}

		private static void GiveReward(int questIndex)
		{
			Terminal val = Object.FindObjectOfType<Terminal>();
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			List<QuestData> value = NetworkHandler.TodaysQuestsData.Value;
			if (questIndex < 0 || questIndex >= value.Count)
			{
				return;
			}
			QuestData value2 = value[questIndex];
			if (!value2.IsRewardGiven)
			{
				val.groupCredits += value2.Reward;
				val.SyncGroupCreditsClientRpc(val.groupCredits, val.numberOfItemsInDropship);
				value2.IsRewardGiven = true;
				value[questIndex] = value2;
				NetworkHandler.TodaysQuestsData.Value = value;
				UpdateTheQuests(value);
				if (Plugin.ConfigOutputDebugLogs.Value)
				{
					Plugin.mls.LogInfo((object)$"{value2.Reward} credits added for the quest: {value2.TargetName}");
				}
			}
		}
	}
	public static class ScrapManager
	{
		[HarmonyPatch(typeof(GrabbableObject), "DiscardItem")]
		public static class ScrapCollectPatch
		{
			[HarmonyPostfix]
			private static void Postfix(GrabbableObject __instance)
			{
				if (__instance.itemProperties.isScrap && __instance.isInShipRoom)
				{
					NetworkHandler.ItemDroppedMessage.SendServer(((NetworkBehaviour)__instance).NetworkObjectId);
				}
			}
		}

		public static List<ScrapData> TodaysScraps = new List<ScrapData>();

		public static List<ScrapPoolEntry> SelectedScrapPool = new List<ScrapPoolEntry>();

		public static void PrepareScrapPool()
		{
			SelectedScrapPool.Clear();
			if (TodaysScraps == null || TodaysScraps.Count == 0)
			{
				return;
			}
			List<ScrapPoolEntry> source = (from s in TodaysScraps
				group s by s.Name).Select(delegate(IGrouping<string, ScrapData> g)
			{
				ScrapPoolEntry result = default(ScrapPoolEntry);
				result.Name = g.Key;
				result.TotalCount = g.Count();
				result.AverageValue = (int)g.Average((ScrapData s) => s.Value);
				return result;
			}).ToList();
			List<ScrapPoolEntry> source2 = source.OrderBy((ScrapPoolEntry x) => Random.value).ToList();
			SelectedScrapPool = source2.Take(5).ToList();
			for (int i = 0; i < SelectedScrapPool.Count; i++)
			{
				ScrapPoolEntry scrapPoolEntry = SelectedScrapPool[i];
				if (Plugin.ConfigOutputDebugLogs.Value)
				{
					Plugin.mls.LogInfo((object)$"[{i + 1}] {scrapPoolEntry.Name} | Count: {scrapPoolEntry.TotalCount} | Avg. Value: ■{scrapPoolEntry.AverageValue}");
				}
			}
		}

		public static void ScanMapForScraps()
		{
			TodaysScraps.Clear();
			GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
			GrabbableObject[] array2 = array;
			foreach (GrabbableObject val in array2)
			{
				if (!((Object)(object)val == (Object)null) && val.itemProperties.isScrap)
				{
					NetworkObject component = ((Component)val).GetComponent<NetworkObject>();
					if (!((Object)(object)component == (Object)null) && component.IsSpawned && !val.isInShipRoom && !val.isHeld)
					{
						TodaysScraps.Add(new ScrapData(val));
					}
				}
			}
			if (Plugin.ConfigOutputDebugLogs.Value)
			{
				Plugin.mls.LogInfo((object)$"Map scanned, {TodaysScraps.Count} scraps found.");
			}
		}

		public static void CheckScrapCollection(ulong netId)
		{
			if (!((NetworkBehaviour)RoundManager.Instance).IsServer)
			{
				return;
			}
			ScrapData scrapData = TodaysScraps.FirstOrDefault((ScrapData s) => s.NetworkId == netId);
			if (scrapData == null || scrapData.IsCollected)
			{
				return;
			}
			List<QuestData> value = NetworkHandler.TodaysQuestsData.Value;
			if (value == null)
			{
				return;
			}
			bool flag = false;
			for (int i = 0; i < value.Count; i++)
			{
				QuestData value2 = value[i];
				if (value2.Type == QuestType.Scrap && value2.TargetName == scrapData.Name)
				{
					value2.CurrentCount++;
					value[i] = value2;
					flag = true;
				}
			}
			if (flag)
			{
				scrapData.IsCollected = true;
				NetworkHandler.TodaysQuestsData.Value = new List<QuestData>(value);
				if (Plugin.ConfigOutputDebugLogs.Value)
				{
					Plugin.mls.LogInfo((object)"Quest list updated on the network.");
				}
			}
		}
	}
}
namespace LethalQuesting.Core
{
	[BepInPlugin("com.fighter.lethalquesting", "Lethal Questing", "1.3.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		[DataContract]
		public class MyConfig : SyncedConfig2<MyConfig>
		{
			[DataMember]
			public SyncedEntry<float> ConfigPercentOfQuota { get; internal set; }

			[DataMember]
			public SyncedEntry<float> ConfigAverageQuestCount { get; internal set; }

			[DataMember]
			public SyncedEntry<bool> ConfigRandomNumberOfQuests { get; internal set; }

			public MyConfig(ConfigFile cfg)
				: base("com.fighter.lethalquesting")
			{
				ConfigPercentOfQuota = SyncedBindingExtensions.BindSyncedEntry<float>(cfg, "Quests", "Rewards Percent of Quota", 0.1f, "Quest rewards use a percentage of your quota to calculate, there are other factors like scrap value and amount too. Default value is 10%.");
				ConfigAverageQuestCount = SyncedBindingExtensions.BindSyncedEntry<float>(cfg, "Quests", "Number of Daily Quests", 1.5f, "Average amount of quests you get assigned per day, the actual amount will vary between 0 and double the value you put here. Values bigger than 2 may not be supported.");
				ConfigRandomNumberOfQuests = SyncedBindingExtensions.BindSyncedEntry<bool>(cfg, "Quests", "Randomize Number of Quests", true, "If enabled, it will use bell curve function and the [Number of Daily Quests] to assign a random amount of quests per day, if disabled it will round [Number of Daily Quests] to the closest integer and assign that many quests every day.");
				ConfigManager.Register<MyConfig>((SyncedConfig2<MyConfig>)(object)this);
			}
		}

		public const string GUID = "com.fighter.lethalquesting";

		public const string Name = "Lethal Questing";

		public const string Version = "1.3.0";

		public static bool IsUIVisible = true;

		public static bool IsEscMenuOpen = false;

		public static TextMeshProUGUI myCustomText;

		public static ManualLogSource mls;

		public static MyConfig CustomConfig { get; set; } = null;


		public static ConfigEntry<bool> ConfigDebugFunctionality { get; set; } = null;


		public static ConfigEntry<bool> ConfigOutputDebugLogs { get; set; } = null;


		public static ConfigEntry<int> ConfigUIWidth { get; set; } = null;


		public static ConfigEntry<int> ConfigUIHeight { get; set; } = null;


		public static ConfigEntry<int> ConfigUIOffsetX { get; set; } = null;


		public static ConfigEntry<int> ConfigUIOffsetY { get; set; } = null;


		public static ConfigEntry<int> ConfigUIFontSize { get; set; } = null;


		private void Awake()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			Harmony val = new Harmony("com.fighter.lethalquesting");
			NetworkHandler.Initialize();
			CustomConfig = new MyConfig(((BaseUnityPlugin)this).Config);
			ConfigOutputDebugLogs = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "Enable Debug Logs", false, "When enabled, it will print debug logs to terminal, any errors will still log regardless of this option.");
			ConfigDebugFunctionality = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "Color Textbox Background", false, "Enables debug features such as making the textbox object visible so that you can see in real-time if you configure offsets and boundaries. (toggle the text once you toggle this option so it updates)");
			ConfigUIHeight = ConfigBindClamp("UI", "TextBox Height", 300, "Height of the textbox in pixels. (860 is whole screen, 0 is nonexistent)", 20, 860);
			ConfigUIWidth = ConfigBindClamp("UI", "TextBox Width", 280, "Width of the textbox in pixels. (520 is whole screen, 0 is nonexistent)", 20, 520);
			ConfigUIOffsetX = ConfigBindClamp("UI", "TextBox Horizontal Offset", 10, "Space between right edge of the screen and right edge of the textbox in pixels. (860 is whole screen, 0 is nonexistent)", 0, 860);
			ConfigUIOffsetY = ConfigBindClamp("UI", "TextBox Vertical Offset", 140, "Space between top of the screen and top of the textbox in pixels. (520 is whole screen, 0 is nonexistent)", 0, 520);
			ConfigUIFontSize = ConfigBindClamp("UI", "Text Font Size", 16, "Font size, if you make it too big make sure to scale the text box width and height too so it displays, it's 16 by default", 4, 120);
			mls = Logger.CreateLogSource("LQuesting");
			mls.LogInfo((object)"Lethal Questing loaded!");
			val.PatchAll();
		}

		public ConfigEntry<int> ConfigBindClamp(string section, string key, int defaultValue, string description, int min, int max)
		{
			ConfigEntry<int> val = ((BaseUnityPlugin)this).Config.Bind<int>(section, key, defaultValue, description);
			val.Value = Mathf.Clamp(val.Value, min, max);
			return val;
		}

		public ConfigEntry<float> ConfigBindClamp(string section, string key, float defaultValue, string description, float min, float max)
		{
			ConfigEntry<float> val = ((BaseUnityPlugin)this).Config.Bind<float>(section, key, defaultValue, description);
			val.Value = Mathf.Clamp(val.Value, min, max);
			return val;
		}

		public static void LogLivingEnemies()
		{
			EnemyAI[] array = Object.FindObjectsOfType<EnemyAI>();
			if (ConfigOutputDebugLogs.Value)
			{
				mls.LogInfo((object)$"--- Current enemy number: {array.Length} ---");
			}
			EnemyAI[] array2 = array;
			foreach (EnemyAI val in array2)
			{
				if (!((Object)(object)val == (Object)null) && !val.isEnemyDead)
				{
					string internalName = (((Object)(object)val.enemyType != (Object)null) ? val.enemyType.enemyName : "Unknown");
					string cleanName = EnemyNameHelper.GetCleanName(internalName);
					float num = (((Object)(object)val.enemyType != (Object)null) ? val.enemyType.PowerLevel : 0f);
					int enemyHP = val.enemyHP;
					if (ConfigOutputDebugLogs.Value)
					{
						mls.LogInfo((object)$"Enemy: {cleanName} | HP: {enemyHP} | Power: {num}");
					}
				}
			}
		}
	}
}