Decompiled source of Ultimate Scanner v1.0.0

Ultimate Scanner.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using ChatCommandAPI;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: AssemblyTitle("Ultimate Scanner")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("1.0.0.0")]
namespace UltimateScan;

internal static class AutoScan
{
	public struct Totals
	{
		public int InAmt;

		public int OutAmt;

		public int InVal;

		public int OutVal;
	}

	public static bool ChatAutoScan;

	public static bool AutoCruiserScan;

	public static bool DayStart;

	public static bool ScanBodies;

	public static bool? SessionScan;

	public static bool? SessionCruiser;

	public static bool FinalScanSetting = true;

	public static bool? SessionFinal;

	public const string DefaultFinalFormat = "<nobr>Collected: {collectedamount}/{totalamount}</nobr> <nobr>Value: {collectedvalue}/{totalvalue}</nobr>";

	public static string FinalFormat = "<nobr>Collected: {collectedamount}/{totalamount}</nobr> <nobr>Value: {collectedvalue}/{totalvalue}</nobr>";

	public const string CruiserUnavailable = "Cruiser Unavailable";

	private static bool _wasLeaving;

	private static bool _finalDone;

	public static string IntervalScan = string.Empty;

	public static string CruiserIntervalScan = string.Empty;

	public static string ScanFormat = string.Empty;

	public static string CruiserFormat = string.Empty;

	public static string AnnounceColor = "#FFFF00";

	public static float DayStartDelay = 2.5f;

	public static float ClientExtraDelay = 3f;

	public static Assembly CruiserAsm;

	public static Action<string> Info;

	public static Action<string> Warn;

	public static bool HookInstalled;

	private static readonly Stopwatch Clock = Stopwatch.StartNew();

	private static string _parsedFrom;

	private static string _parsedCruiserFrom;

	private static readonly List<float> Times = new List<float>();

	private static readonly List<float> Steps = new List<float>();

	private static readonly List<float> CTimes = new List<float>();

	private static readonly List<float> CSteps = new List<float>();

	private static FieldInfo _deactivated;

	private static FieldInfo _inFactory;

	private static bool _fieldsLooked;

	private static Type _bodyType;

	private static bool _noticeFlip;

	private static bool _flip;

	private static double _hookAt = -100.0;

	private static int _lastFrame = -1;

	private static bool _wasOrbit = true;

	private static bool _dayArmed;

	private static bool _dayDone;

	private static double _armedAt;

	private static double _readyCheckAt;

	private static Totals _lastTotals;

	private static bool _haveLast;

	private static double _stableSince;

	private static float _lastElapsed = -1f;

	private static bool _clockWarned;

	private static readonly HashSet<int> _baseline = new HashSet<int>();

	private static bool _baselineSet;

	public static bool FinalScanOn
	{
		get
		{
			bool? sessionFinal = SessionFinal;
			return (!sessionFinal.HasValue) ? FinalScanSetting : sessionFinal.Value;
		}
	}

	public static bool ScanOn
	{
		get
		{
			bool? sessionScan = SessionScan;
			return (!sessionScan.HasValue) ? ChatAutoScan : sessionScan.Value;
		}
	}

	public static bool CruiserOn
	{
		get
		{
			bool? sessionCruiser = SessionCruiser;
			return (!sessionCruiser.HasValue) ? AutoCruiserScan : sessionCruiser.Value;
		}
	}

	private static double Now()
	{
		return Clock.Elapsed.TotalSeconds;
	}

	public static void ParseSchedule(string text, List<float> times, List<float> steps, List<string> bad)
	{
		times.Clear();
		steps.Clear();
		if (text == null)
		{
			return;
		}
		string[] array = text.Split(',');
		foreach (string text2 in array)
		{
			string text3 = text2.Trim().ToLowerInvariant();
			if (text3.Length == 0)
			{
				continue;
			}
			Match match = Regex.Match(text3, "^(\\d{1,2})(?::(\\d{2}))?\\s*(am|pm)$");
			if (match.Success)
			{
				int num = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture) % 12;
				int num2 = (match.Groups[2].Success ? int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture) : 0);
				if (match.Groups[3].Value == "pm")
				{
					num += 12;
				}
				float num3 = (float)num * 60f + (float)num2;
				if (num3 < 360f)
				{
					num3 += 1440f;
				}
				times.Add(num3);
				continue;
			}
			match = Regex.Match(text3, "^(\\d{1,2}):(\\d{2})$");
			float result;
			if (match.Success)
			{
				float num4 = (float)int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture) * 60f + (float)int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
				if (num4 < 360f)
				{
					num4 += 1440f;
				}
				times.Add(num4);
			}
			else if (float.TryParse(text3, NumberStyles.Float, CultureInfo.InvariantCulture, out result) && result > 0f)
			{
				steps.Add(result);
			}
			else
			{
				bad?.Add(text2.Trim());
			}
		}
	}

	public static int Crossed(List<float> times, List<float> steps, float lastElapsed, float elapsed)
	{
		int num = 0;
		float num2 = lastElapsed + 360f;
		float num3 = elapsed + 360f;
		foreach (float time in times)
		{
			float num4 = time;
			if (num2 < num4 && num3 >= num4)
			{
				num++;
			}
		}
		foreach (float step in steps)
		{
			float num5 = step;
			double num6 = (double)num5 * 60.0;
			if (Math.Floor((double)elapsed / num6) > Math.Floor((double)lastElapsed / num6))
			{
				num++;
			}
		}
		return num;
	}

	private static string Fmt(string format, params string[] kv)
	{
		string text = (format ?? string.Empty).Replace("\\n", "\n");
		for (int i = 0; i + 1 < kv.Length; i += 2)
		{
			text = Regex.Replace(text, Regex.Escape("{" + kv[i] + "}"), kv[i + 1].Replace("$", "$$"), RegexOptions.IgnoreCase);
		}
		return text;
	}

	public static string ScanText(string format, int inAmt, int outAmt, int inVal, int outVal)
	{
		return Fmt(format, "insideamount", inAmt.ToString(), "outsideamount", outAmt.ToString(), "insidevalue", inVal.ToString(), "outsidevalue", outVal.ToString());
	}

	public static string CruiserText(string format, int cruiserValue, int moonValue, int cruiserCount, int moonCount)
	{
		return Fmt(format, "insidecruiseramount", cruiserValue.ToString(), "totalinterior", moonValue.ToString(), "Cruiseramount", cruiserCount.ToString(), "TotalinteriorCount", moonCount.ToString());
	}

	private static bool IsBody(object g)
	{
		if (_bodyType == null)
		{
			_bodyType = Rf.T("RagdollGrabbableObject");
		}
		return _bodyType != null && _bodyType.IsInstanceOfType(g);
	}

	public static float OutsideHeight()
	{
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			Type type = Rf.T("EntranceTeleport");
			MethodInfo methodInfo = ((!(type == null)) ? typeof(Object).GetMethod("FindObjectsOfType", new Type[1] { typeof(Type) }) : null);
			Array array = ((!(methodInfo == null)) ? (methodInfo.Invoke(null, new object[1] { type }) as Array) : null);
			float num = 0f;
			int num2 = 0;
			if (array != null)
			{
				foreach (object item in array)
				{
					if (Rf.Bool(item, "isEntranceToBuilding", def: false))
					{
						object obj = Rf.Get(item, "exitPoint");
						Transform val = (Transform)((obj is Transform) ? obj : null);
						if (!((Object)(object)val == (Object)null))
						{
							num += val.position.y;
							num2++;
						}
					}
				}
			}
			if (num2 > 0)
			{
				return num / (float)num2 + 100f;
			}
		}
		catch (Exception)
		{
		}
		return -100f;
	}

	private static void LookFields()
	{
		if (_fieldsLooked)
		{
			return;
		}
		_fieldsLooked = true;
		try
		{
			BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
			_deactivated = typeof(GrabbableObject).GetField("deactivated", bindingAttr);
			_inFactory = typeof(GrabbableObject).GetField("isInFactory", bindingAttr);
		}
		catch (Exception)
		{
		}
	}

	private static bool Countable(GrabbableObject g)
	{
		if ((Object)(object)g == (Object)null || (Object)(object)g.itemProperties == (Object)null || !g.itemProperties.isScrap || g.itemUsedUp)
		{
			return false;
		}
		if (_deactivated != null && UltimateStyle.Fast(_deactivated, g))
		{
			return false;
		}
		if (!ScanBodies && IsBody(g))
		{
			return false;
		}
		return true;
	}

	public static Totals Count()
	{
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		Totals result = default(Totals);
		LookFields();
		GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
		GameObject val = GameObject.Find("Environment/HangarShip");
		Component[] array2 = Vehicles();
		float num = OutsideHeight();
		foreach (GrabbableObject val2 in array)
		{
			if (!Countable(val2) || val2.isInShipRoom || ((Object)(object)val != (Object)null && ((Component)val2).transform.IsChildOf(val.transform)))
			{
				continue;
			}
			bool flag = false;
			for (int j = 0; j < array2.Length; j++)
			{
				if (flag)
				{
					break;
				}
				flag = ((Component)val2).transform.IsChildOf(array2[j].transform);
			}
			if (!flag)
			{
				if ((_inFactory == null || UltimateStyle.Fast(_inFactory, val2)) && ((Component)val2).transform.position.y <= num)
				{
					result.InAmt++;
					result.InVal += val2.scrapValue;
				}
				else
				{
					result.OutAmt++;
					result.OutVal += val2.scrapValue;
				}
			}
		}
		return result;
	}

	private static Component[] Vehicles()
	{
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Expected O, but got Unknown
		try
		{
			Type type = Rf.T("VehicleController");
			MethodInfo methodInfo = ((!(type == null)) ? typeof(Object).GetMethod("FindObjectsOfType", new Type[1] { typeof(Type) }) : null);
			Array array = ((!(methodInfo == null)) ? (methodInfo.Invoke(null, new object[1] { type }) as Array) : null);
			if (array == null)
			{
				return (Component[])(object)new Component[0];
			}
			Component[] array2 = (Component[])(object)new Component[array.Length];
			for (int i = 0; i < array2.Length; i++)
			{
				array2[i] = (Component)array.GetValue(i);
			}
			return array2;
		}
		catch (Exception)
		{
			return (Component[])(object)new Component[0];
		}
	}

	private static bool CruiserNumbers(out int cv, out int mv, out int cc, out int mc)
	{
		cv = (mv = (cc = (mc = 0)));
		if (CruiserAsm == null)
		{
			return false;
		}
		Type type = CruiserAsm.GetType("CruiserScrapCounter.LootTracker");
		if (type == null)
		{
			return false;
		}
		MethodInfo method = type.GetMethod("IsDisabledMoon", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		MethodInfo method2 = type.GetMethod("Count", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		if (method != null && (bool)method.Invoke(null, null))
		{
			return false;
		}
		Type type2 = Rf.T("VehicleController");
		if (type2 == null)
		{
			return false;
		}
		MethodInfo method3 = typeof(Object).GetMethod("FindObjectOfType", new Type[1] { typeof(Type) });
		object obj = ((!(method3 == null)) ? method3.Invoke(null, new object[1] { type2 }) : null);
		if (Rf.Dead(obj))
		{
			return false;
		}
		object[] array = new object[5] { obj, 0, 0, 0, 0 };
		method2.Invoke(null, array);
		cv = (int)array[1];
		cc = (int)array[2];
		mv = (int)array[3];
		mc = (int)array[4];
		return true;
	}

	public static void Notice(string message)
	{
		try
		{
			bool noticeFlip = _noticeFlip;
			_noticeFlip = !_noticeFlip;
			Rf.Call(Rf.Instance("HUDManager"), "AddChatMessage", Decorate(message, noticeFlip));
		}
		catch (Exception)
		{
		}
	}

	public static string RunCommand(string cmd)
	{
		if (Game.InOrbit() || (!Game.Landed() && !Game.Leaving()))
		{
			return "The ship is not on a moon.";
		}
		if (cmd == "scan")
		{
			if (Game.ExcludedMoon())
			{
				return "There is no scrap to scan on this moon.";
			}
			Totals totals = Count();
			return (!Send(ScanText(ScanFormat, totals.InAmt, totals.OutAmt, totals.InVal, totals.OutVal))) ? "The message could not be sent." : null;
		}
		if (!CruiserNumbers(out var cv, out var mv, out var cc, out var mc))
		{
			return "Cruiser Unavailable";
		}
		return (!Send(CruiserText(CruiserFormat, cv, mv, cc, mc))) ? "The message could not be sent." : null;
	}

	public static string NormalizeColor(string hex)
	{
		if (hex == null)
		{
			return null;
		}
		hex = hex.Trim().TrimStart('#');
		if (hex.Length != 6 && hex.Length != 8)
		{
			return null;
		}
		string text = hex;
		foreach (char character in text)
		{
			if (!Uri.IsHexDigit(character))
			{
				return null;
			}
		}
		return "#" + hex.ToUpperInvariant();
	}

	public static string Colorize(string message, string hex)
	{
		string text = NormalizeColor(hex);
		return (text != null) ? ("<color=" + text + ">" + message + "</color>") : message;
	}

	public static string FlipBlue(string color)
	{
		byte b = Convert.ToByte(color.Substring(5, 2), 16);
		return color.Substring(0, 5) + (b ^ 1).ToString("X2") + color.Substring(7);
	}

	public static string Decorate(string message)
	{
		bool flip = _flip;
		_flip = !_flip;
		return Decorate(message, flip);
	}

	public static string Decorate(string message, bool flip)
	{
		string text = NormalizeColor(AnnounceColor);
		if (text == null)
		{
			return (!flip) ? message : ("<alpha=#FE>" + message + "<alpha=#FF>");
		}
		return "<color=" + ((!flip) ? text : FlipBlue(text)) + ">" + message + "</color>";
	}

	public static bool Send(string message)
	{
		try
		{
			object obj = Rf.Instance("HUDManager");
			if (obj == null)
			{
				return false;
			}
			message = Decorate(message);
			try
			{
				Rf.Call(obj, "AddTextMessageServerRpc", message);
			}
			catch (MissingMethodException)
			{
				Rf.Call(obj, "AddTextToChatOnServer", message, -1);
			}
			return true;
		}
		catch (Exception ex2)
		{
			if (Warn != null)
			{
				Warn("Could not send the chat message: " + (ex2.InnerException ?? ex2).Message);
			}
			return false;
		}
	}

	public static void Install(object harmony, MethodInfo patch, Type harmonyMethodType)
	{
		try
		{
			Type type = Rf.T("StartOfRound");
			MethodInfo methodInfo = null;
			if (type != null)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo2 in methods)
				{
					if (methodInfo2.Name == "openingDoorsSequence")
					{
						methodInfo = methodInfo2;
						break;
					}
				}
			}
			if (methodInfo == null)
			{
				throw new MissingMethodException("StartOfRound.openingDoorsSequence");
			}
			object[] array = new object[patch.GetParameters().Length];
			array[0] = methodInfo;
			array[2] = Activator.CreateInstance(harmonyMethodType, typeof(AutoScan).GetMethod("OnLanding", BindingFlags.Static | BindingFlags.NonPublic));
			patch.Invoke(harmony, array);
			HookInstalled = true;
		}
		catch (Exception ex)
		{
			if (Warn != null)
			{
				Warn("AutoScan: landing hook unavailable (" + (ex.InnerException ?? ex).Message + "); the delay counts from leaving orbit instead.");
			}
		}
	}

	private static void OnLanding()
	{
		OnLandingForTests();
	}

	public static void OnLandingForTests()
	{
		_hookAt = Now();
		_armedAt = _hookAt;
		_readyCheckAt = 0.0;
		_haveLast = false;
		_wasOrbit = false;
		_dayDone = false;
		_dayArmed = true;
		TakeBaseline();
	}

	public static void Update()
	{
		int frameCount = Time.frameCount;
		if (frameCount == _lastFrame)
		{
			return;
		}
		_lastFrame = frameCount;
		try
		{
			CheckFinal();
			CheckBaseline();
			if (!ScanOn && !CruiserOn && !DayStart)
			{
				_dayArmed = false;
				return;
			}
			object obj = Game.Round();
			if (obj == null)
			{
				_wasOrbit = true;
				_dayArmed = false;
				_lastElapsed = -1f;
				return;
			}
			bool flag = Game.InOrbit();
			if (flag && Now() - _hookAt > 10.0)
			{
				_dayArmed = false;
				_lastElapsed = -1f;
				_wasOrbit = true;
			}
			else
			{
				if (flag)
				{
					return;
				}
				if (_wasOrbit)
				{
					_wasOrbit = false;
					_dayDone = false;
					_haveLast = false;
					_lastElapsed = -1f;
					if (!HookInstalled)
					{
						_dayArmed = true;
						_armedAt = Now();
					}
				}
				if (Game.Leaving())
				{
					return;
				}
				if (Game.ExcludedMoon())
				{
					_dayDone = true;
					_dayArmed = false;
					return;
				}
				if (DayStart && _dayArmed && !_dayDone)
				{
					DayStartScan();
				}
				if (Game.Landed() && (Game.IsHost() || SessionScan == true || SessionCruiser == true))
				{
					Schedule();
				}
			}
		}
		catch (Exception ex)
		{
			if (Warn != null && !_clockWarned)
			{
				_clockWarned = true;
				Warn("Auto scan error: " + ex.Message);
			}
		}
	}

	private static void DayStartScan()
	{
		double num = Now();
		double num2 = (double)Math.Max(0f, DayStartDelay) + ((!Game.IsHost()) ? ((double)Math.Max(0f, ClientExtraDelay)) : 0.0);
		if (num - _armedAt < num2 || num < _readyCheckAt || (!Game.Landed() && num - _armedAt < num2 + 25.0))
		{
			return;
		}
		_readyCheckAt = num + 0.3;
		object obj = Rf.Get(Rf.Instance("RoundManager"), "dungeonCompletedGenerating");
		if (obj is bool && !(bool)obj)
		{
			return;
		}
		Totals lastTotals = Count();
		if (!_haveLast || lastTotals.InAmt != _lastTotals.InAmt || lastTotals.OutAmt != _lastTotals.OutAmt || lastTotals.InVal != _lastTotals.InVal || lastTotals.OutVal != _lastTotals.OutVal)
		{
			_lastTotals = lastTotals;
			_haveLast = true;
			_stableSince = num;
		}
		else
		{
			if (lastTotals.InAmt == 0 && lastTotals.OutAmt == 0 && num - _armedAt < num2 + 20.0)
			{
				return;
			}
			_dayDone = true;
			_dayArmed = false;
			string text = ScanText(ScanFormat, lastTotals.InAmt, lastTotals.OutAmt, lastTotals.InVal, lastTotals.OutVal);
			if (Game.IsHost())
			{
				if (Send(text) && Info != null)
				{
					Info("Day start scan sent: " + text);
				}
				return;
			}
			Notice(text);
			if (Info != null)
			{
				Info("Day start scan shown in your chat: " + text);
			}
		}
	}

	private static void Schedule()
	{
		bool flag = Game.IsHost();
		bool flag2 = (flag ? ScanOn : (SessionScan == true));
		bool flag3 = (flag ? CruiserOn : (SessionCruiser == true));
		if (!flag2 && !flag3)
		{
			return;
		}
		if (!Game.DayMinutes(out var elapsed, out var _))
		{
			if (!_clockWarned && Warn != null)
			{
				_clockWarned = true;
				Warn("The in-game clock could not be read: scheduled scans are off.");
			}
			return;
		}
		if (_lastElapsed < 0f || elapsed < _lastElapsed)
		{
			_lastElapsed = elapsed;
			return;
		}
		string text = IntervalScan ?? string.Empty;
		string text2 = CruiserIntervalScan ?? string.Empty;
		if (text != _parsedFrom)
		{
			_parsedFrom = text;
			ParseSchedule(text, Times, Steps, null);
		}
		if (text2 != _parsedCruiserFrom)
		{
			_parsedCruiserFrom = text2;
			ParseSchedule(text2, CTimes, CSteps, null);
		}
		float lastElapsed = _lastElapsed;
		_lastElapsed = elapsed;
		if (flag2 && Crossed(Times, Steps, lastElapsed, elapsed) > 0)
		{
			Totals totals = Count();
			Post(ScanText(ScanFormat, totals.InAmt, totals.OutAmt, totals.InVal, totals.OutVal));
		}
		if (flag3 && Crossed(CTimes, CSteps, lastElapsed, elapsed) > 0 && CruiserNumbers(out var cv, out var mv, out var cc, out var mc))
		{
			Post(CruiserText(CruiserFormat, cv, mv, cc, mc));
		}
	}

	private static void CheckBaseline()
	{
		if (Game.InOrbit())
		{
			_baselineSet = false;
		}
		else if (!_baselineSet)
		{
			TakeBaseline();
		}
	}

	private static void TakeBaseline()
	{
		try
		{
			_baseline.Clear();
			LookFields();
			GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
			GameObject val = GameObject.Find("Environment/HangarShip");
			Component[] array2 = Vehicles();
			foreach (GrabbableObject val2 in array)
			{
				if (Countable(val2))
				{
					bool flag = val2.isInShipRoom || ((Object)(object)val != (Object)null && ((Component)val2).transform.IsChildOf(val.transform));
					int num = 0;
					while (!flag && num < array2.Length)
					{
						flag = ((Component)val2).transform.IsChildOf(array2[num].transform);
						num++;
					}
					if (flag)
					{
						_baseline.Add(((Object)val2).GetInstanceID());
					}
				}
			}
			_baselineSet = true;
		}
		catch (Exception)
		{
			_baselineSet = false;
		}
	}

	private static bool Magneted(Component car, GameObject ship)
	{
		object obj = Rf.Get(car, "magnetedToShip");
		if (obj is bool)
		{
			return (bool)obj;
		}
		return (Object)(object)ship != (Object)null && car.transform.IsChildOf(ship.transform);
	}

	public static void FinalNumbers(out int collectedAmt, out int totalAmt, out int collectedVal, out int totalVal, out int cars, out int magneted)
	{
		collectedAmt = (totalAmt = (collectedVal = (totalVal = (cars = (magneted = 0)))));
		LookFields();
		GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
		GameObject val = GameObject.Find("Environment/HangarShip");
		Component[] array2 = Vehicles();
		bool[] array3 = new bool[array2.Length];
		cars = array2.Length;
		for (int i = 0; i < array2.Length; i++)
		{
			array3[i] = Magneted(array2[i], val);
			if (array3[i])
			{
				magneted++;
			}
		}
		foreach (GrabbableObject val2 in array)
		{
			if (!Countable(val2) || _baseline.Contains(((Object)val2).GetInstanceID()))
			{
				continue;
			}
			bool flag = val2.isInShipRoom || ((Object)(object)val != (Object)null && ((Component)val2).transform.IsChildOf(val.transform));
			if (!flag)
			{
				for (int k = 0; k < array2.Length; k++)
				{
					if (((Component)val2).transform.IsChildOf(array2[k].transform))
					{
						flag = array3[k];
						break;
					}
				}
			}
			totalAmt++;
			totalVal += val2.scrapValue;
			if (flag)
			{
				collectedAmt++;
				collectedVal += val2.scrapValue;
			}
		}
	}

	public static string FinalText(string format, int collectedAmt, int totalAmt, int collectedVal, int totalVal)
	{
		return Fmt(format, "collectedamount", collectedAmt.ToString(), "totalamount", totalAmt.ToString(), "collectedvalue", collectedVal.ToString(), "totalvalue", totalVal.ToString());
	}

	private static void CheckFinal()
	{
		if (!Game.Leaving() || Game.InOrbit())
		{
			_wasLeaving = false;
			_finalDone = false;
		}
		else if (!_wasLeaving)
		{
			_wasLeaving = true;
			FireFinal();
		}
	}

	public static void FireFinal()
	{
		try
		{
			if (_finalDone || !FinalScanOn || Game.InOrbit())
			{
				return;
			}
			_finalDone = true;
			if (!Game.ExcludedMoon())
			{
				FinalNumbers(out var collectedAmt, out var totalAmt, out var collectedVal, out var totalVal, out var cars, out var magneted);
				if (Info != null)
				{
					Info("Final scan: collected " + collectedAmt + "/" + totalAmt + ", value " + collectedVal + "/" + totalVal + ", Cruisers " + cars + " (magneted " + magneted + ").");
				}
				if (totalAmt != 0)
				{
					Post(FinalText(FinalFormat, collectedAmt, totalAmt, collectedVal, totalVal));
				}
			}
		}
		catch (Exception)
		{
		}
	}

	public static string SetFinal(bool? want)
	{
		bool flag = ((!want.HasValue) ? (!FinalScanOn) : want.Value);
		SessionFinal = flag;
		if (!flag)
		{
			return "FinalScan off.";
		}
		return "FinalScan on" + ((!Game.IsHost()) ? " (your own chat only)" : string.Empty) + ": the final stats are sent when the ship starts leaving.";
	}

	public static void EndSession()
	{
		SessionScan = (SessionCruiser = null);
		SessionFinal = null;
		_wasLeaving = false;
		_finalDone = false;
	}

	private static void Post(string msg)
	{
		if (Game.IsHost())
		{
			Send(msg);
		}
		else
		{
			Notice(msg);
		}
	}

	private static string Describe(string cfg)
	{
		cfg = (cfg ?? string.Empty).Trim();
		if (int.TryParse(cfg, out var result) && result > 0)
		{
			return (result != 1) ? ("every " + result + " hours") : "every hour";
		}
		return cfg;
	}

	public static string SetSession(bool? want)
	{
		return SetSession(cruiser: false, want);
	}

	public static string SetSession(bool cruiser, bool? want)
	{
		bool flag = ((!want.HasValue) ? (!((!cruiser) ? ScanOn : CruiserOn)) : want.Value);
		if (cruiser)
		{
			SessionCruiser = flag;
		}
		else
		{
			SessionScan = flag;
		}
		_lastElapsed = -1f;
		string text = ((!cruiser) ? "AutoScan" : "AutoScan (Cruiser)");
		if (!flag)
		{
			return text + " off.";
		}
		string text2 = ((!cruiser) ? IntervalScan : CruiserIntervalScan) ?? string.Empty;
		string text3 = ((!cruiser) ? "Interval Scan" : "Cruiser Interval Scan");
		if (text2.Trim().Length == 0)
		{
			return text + " on, but " + text3 + " in the config is empty.";
		}
		return text + " on" + ((!Game.IsHost()) ? " (your own chat only)" : string.Empty) + ": " + Describe(text2) + ".";
	}

	public static void ResetForTests()
	{
		HookInstalled = false;
		_flip = false;
		_hookAt = -100.0;
		_lastFrame = -1;
		_wasOrbit = true;
		_dayArmed = (_dayDone = false);
		_haveLast = false;
		_lastElapsed = -1f;
		_parsedFrom = null;
		ClientExtraDelay = 3f;
		SessionScan = null;
		SessionCruiser = null;
		SessionFinal = null;
		FinalScanSetting = true;
		FinalFormat = "<nobr>Collected: {collectedamount}/{totalamount}</nobr> <nobr>Value: {collectedvalue}/{totalvalue}</nobr>";
		_wasLeaving = false;
		_finalDone = false;
		_parsedCruiserFrom = null;
		_baseline.Clear();
		_baselineSet = false;
	}
}
internal static class ChatCmds
{
	public static void Register()
	{
		new ScanCommand();
		new OvertimeCommand();
		new AutoScanCommand();
		new FinalScanCommand();
	}
}
internal sealed class ScanCommand : Command
{
	public override string Name => "Scan";

	public override string Description => "Posts the scrap count to everyone's chat: inside / outside the facility. Add -c for the Cruiser report.";

	public override string Command => "scan";

	public override string[] Aliases => new string[0];

	public override string[] Syntax => new string[2]
	{
		string.Empty,
		"-c"
	};

	public override void Invoke(string args)
	{
		//IL_0049: 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)
		string text = (args ?? string.Empty).Trim().ToLowerInvariant();
		string cmd;
		if (text.Length == 0)
		{
			cmd = "scan";
		}
		else
		{
			if (!(text == "-c"))
			{
				throw new InvalidArgumentsException();
			}
			cmd = "cruiser";
		}
		string text2 = AutoScan.RunCommand(cmd);
		if (text2 == "Cruiser Unavailable")
		{
			AutoScan.Notice(text2);
		}
		else if (text2 != null)
		{
			throw new CommandException(text2);
		}
	}
}
internal sealed class OvertimeCommand : Command
{
	public override string Name => "Overtime";

	public override string Description => "At the Company: posts the overtime bonus to everyone's chat.";

	public override string Command => "overtime";

	public override string[] Aliases => new string[0];

	public override void Invoke(string args)
	{
		//IL_001c: 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)
		if (!string.IsNullOrEmpty((args ?? string.Empty).Trim()))
		{
			throw new InvalidArgumentsException();
		}
		string text = Run();
		if (text != null)
		{
			throw new CommandException(text);
		}
	}

	public static string Run()
	{
		if (Game.InOrbit() || !Game.AtCompany())
		{
			return "This only works at the Company.";
		}
		int num = QuotaTracker.OvertimeNow();
		if (num < 0)
		{
			return "Could not read the quota. Try again in a moment.";
		}
		if (num <= 0)
		{
			AutoScan.Notice("No overtime bonus.");
			return null;
		}
		return (!AutoScan.Send("Overtime Bonus: " + num)) ? "The message could not be sent." : null;
	}
}
internal sealed class AutoScanCommand : Command
{
	public override string Name => "AutoScan";

	public override string Description => "Scheduled in/out scan on or off for this game (Interval Scan in the config). Add -c for the Cruiser scan (Cruiser Interval Scan). Settings file is not changed.";

	public override string Command => "autoscan";

	public override string[] Aliases => new string[0];

	public override string[] Syntax => new string[6]
	{
		string.Empty,
		"on",
		"off",
		"-c",
		"-c on",
		"-c off"
	};

	public override void Invoke(string args)
	{
		ScanArgs.Parse(args, out var cruiser, out var want);
		AutoScan.Notice(AutoScan.SetSession(cruiser, want));
	}
}
internal static class ScanArgs
{
	public static void Parse(string args, out bool cruiser, out bool? want)
	{
		//IL_006d: 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)
		string[] array = (args ?? string.Empty).Trim().ToLowerInvariant().Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
		cruiser = array.Length > 0 && array[0] == "-c";
		int num = (cruiser ? 1 : 0);
		want = null;
		if (array.Length > num + 1)
		{
			throw new InvalidArgumentsException();
		}
		if (array.Length != num + 1)
		{
			return;
		}
		if (array[num] == "on")
		{
			want = true;
			return;
		}
		if (array[num] == "off")
		{
			want = false;
			return;
		}
		throw new InvalidArgumentsException();
	}
}
internal sealed class FinalScanCommand : Command
{
	public override string Name => "FinalScan";

	public override string Description => "Turns the final stats (sent to chat when the ship starts leaving) off or on for this game. Settings file is not changed.";

	public override string Command => "finalscan";

	public override string[] Aliases => new string[0];

	public override string[] Syntax => new string[3]
	{
		string.Empty,
		"on",
		"off"
	};

	public override void Invoke(string args)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		ScanArgs.Parse(args, out var cruiser, out var want);
		if (cruiser)
		{
			throw new InvalidArgumentsException();
		}
		AutoScan.Notice(AutoScan.SetFinal(want));
	}
}
internal static class CruiserWatch
{
	private sealed class Watched
	{
		public Component C;

		public bool Last;

		public double Until;
	}

	private const double Seconds = 2.0;

	private const int MaxItems = 64;

	private static readonly List<Watched> Items = new List<Watched>();

	private static Transform _cruiser;

	private static double _nextFind;

	public static Func<Component, bool> Probe;

	public static int Count => Items.Count;

	public static void Clear()
	{
		Items.Clear();
		_cruiser = null;
		_nextFind = 0.0;
	}

	public static void Add(object o, double now)
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Expected O, but got Unknown
		try
		{
			if (!(o is GrabbableObject))
			{
				return;
			}
			Component val = (Component)o;
			if (Rf.Dead(val))
			{
				return;
			}
			for (int i = 0; i < Items.Count; i++)
			{
				if (object.ReferenceEquals(Items[i].C, val))
				{
					Items[i].Until = now + 2.0;
					return;
				}
			}
			if (Items.Count >= 64)
			{
				Items.RemoveAt(0);
			}
			Items.Add(new Watched
			{
				C = val,
				Last = InCruiser(val, now),
				Until = now + 2.0
			});
		}
		catch (Exception)
		{
		}
	}

	public static bool Poll(double now)
	{
		if (Items.Count == 0)
		{
			return false;
		}
		bool result = false;
		for (int num = Items.Count - 1; num >= 0; num--)
		{
			Watched watched = Items[num];
			if (Rf.Dead(watched.C) || now > watched.Until)
			{
				Items.RemoveAt(num);
			}
			else
			{
				bool flag = InCruiser(watched.C, now);
				if (flag != watched.Last)
				{
					watched.Last = flag;
					result = true;
				}
			}
		}
		return result;
	}

	private static bool InCruiser(Component c, double now)
	{
		try
		{
			Func<Component, bool> probe = Probe;
			if (probe != null)
			{
				return probe(c);
			}
			if (Rf.Dead(_cruiser) && now >= _nextFind)
			{
				_cruiser = null;
				_nextFind = now + 1.0;
				Type type = Rf.T("VehicleController");
				Component val = (Component)((!(type == null)) ? /*isinst with value type is only supported in some contexts*/: null);
				if (!Rf.Dead(val))
				{
					_cruiser = val.transform;
				}
			}
			return !Rf.Dead(_cruiser) && c.transform.IsChildOf(_cruiser);
		}
		catch (Exception)
		{
			return false;
		}
	}
}
internal static class DeadHud
{
	private static readonly Dictionary<GameObject, Transform> Original = new Dictionary<GameObject, Transform>();

	public static bool Active => Original.Count > 0;

	public static bool IsLifted(GameObject go)
	{
		return (Object)(object)go != (Object)null && Original.ContainsKey(go);
	}

	public static bool HiddenByParent(GameObject go)
	{
		if ((Object)(object)go == (Object)null)
		{
			return false;
		}
		Transform parent = go.transform.parent;
		return (Object)(object)parent != (Object)null && !((Component)parent).gameObject.activeInHierarchy;
	}

	public static int Lift(IEnumerable<GameObject> rows)
	{
		int num = 0;
		foreach (GameObject row in rows)
		{
			try
			{
				if (!((Object)(object)row == (Object)null) && !Original.ContainsKey(row) && HiddenByParent(row))
				{
					Transform parent = row.transform.parent;
					while ((Object)(object)parent != (Object)null && !((Component)parent).gameObject.activeInHierarchy)
					{
						parent = parent.parent;
					}
					if (!((Object)(object)parent == (Object)null))
					{
						Original[row] = row.transform.parent;
						row.transform.SetParent(parent, true);
						num++;
					}
				}
			}
			catch (Exception)
			{
			}
		}
		return num;
	}

	public static void Restore()
	{
		List<GameObject> list = new List<GameObject>(Original.Keys);
		foreach (GameObject item in list)
		{
			try
			{
				Transform val = Original[item];
				if ((Object)(object)item != (Object)null && (Object)(object)val != (Object)null)
				{
					item.transform.SetParent(val, true);
				}
			}
			catch (Exception)
			{
			}
			Original.Remove(item);
		}
	}
}
internal static class Rf
{
	private const BindingFlags All = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;

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

	private static readonly Dictionary<Type, Dictionary<string, MemberInfo>> _members = new Dictionary<Type, Dictionary<string, MemberInfo>>();

	public static Type T(string name)
	{
		if (_types.TryGetValue(name, out var value))
		{
			return value;
		}
		try
		{
			value = Type.GetType(name + ", Assembly-CSharp");
		}
		catch (Exception)
		{
			value = null;
		}
		_types[name] = value;
		return value;
	}

	private static MemberInfo Find(Type t, string name)
	{
		if (!_members.TryGetValue(t, out var value))
		{
			value = new Dictionary<string, MemberInfo>();
			_members[t] = value;
		}
		if (value.TryGetValue(name, out var value2))
		{
			return value2;
		}
		Type type = t;
		while (type != null && value2 == null)
		{
			value2 = type.GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
			if (value2 == null)
			{
				value2 = type.GetProperty(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
			}
			type = type.BaseType;
		}
		value[name] = value2;
		return value2;
	}

	public static object Get(object o, string name)
	{
		if (o == null)
		{
			return null;
		}
		try
		{
			MemberInfo memberInfo = Find(o.GetType(), name);
			FieldInfo fieldInfo = memberInfo as FieldInfo;
			if (fieldInfo != null)
			{
				return fieldInfo.GetValue((!fieldInfo.IsStatic) ? o : null);
			}
			PropertyInfo propertyInfo = memberInfo as PropertyInfo;
			if (propertyInfo != null)
			{
				return propertyInfo.GetValue(o, null);
			}
		}
		catch (Exception)
		{
		}
		return null;
	}

	public static bool Set(object o, string name, object value)
	{
		if (o == null)
		{
			return false;
		}
		try
		{
			MemberInfo memberInfo = Find(o.GetType(), name);
			FieldInfo fieldInfo = memberInfo as FieldInfo;
			if (fieldInfo != null)
			{
				fieldInfo.SetValue((!fieldInfo.IsStatic) ? o : null, value);
				return true;
			}
			PropertyInfo propertyInfo = memberInfo as PropertyInfo;
			if (propertyInfo != null)
			{
				propertyInfo.SetValue(o, value, null);
				return true;
			}
		}
		catch (Exception)
		{
		}
		return false;
	}

	public static object Static(string typeName, string name)
	{
		Type type = T(typeName);
		if (type == null)
		{
			return null;
		}
		try
		{
			MemberInfo memberInfo = Find(type, name);
			FieldInfo fieldInfo = memberInfo as FieldInfo;
			if (fieldInfo != null)
			{
				return fieldInfo.GetValue(null);
			}
			PropertyInfo propertyInfo = memberInfo as PropertyInfo;
			if (propertyInfo != null)
			{
				return propertyInfo.GetValue(null, null);
			}
		}
		catch (Exception)
		{
		}
		return null;
	}

	public static object Instance(string typeName)
	{
		object obj = Static(typeName, "Instance");
		return (!Dead(obj)) ? obj : null;
	}

	public static bool Bool(object o, string name, bool def)
	{
		object obj = Get(o, name);
		return (!(obj is bool)) ? def : ((bool)obj);
	}

	public static int Int(object o, string name, int def)
	{
		object obj = Get(o, name);
		return (!(obj is int)) ? def : ((int)obj);
	}

	public static float Float(object o, string name, float def)
	{
		object obj = Get(o, name);
		if (obj is float)
		{
			return (float)obj;
		}
		if (obj is int)
		{
			return (int)obj;
		}
		return def;
	}

	public static bool Dead(object o)
	{
		if (o == null)
		{
			return true;
		}
		Object val = (Object)((o is Object) ? o : null);
		return val != (Object)null && val == (Object)null;
	}

	public static object Call(object o, string name, params object[] args)
	{
		if (o == null)
		{
			return null;
		}
		MethodInfo[] methods = o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
		foreach (MethodInfo methodInfo in methods)
		{
			if (methodInfo.Name != name)
			{
				continue;
			}
			ParameterInfo[] parameters = methodInfo.GetParameters();
			if (parameters.Length < args.Length)
			{
				continue;
			}
			object[] array = new object[parameters.Length];
			bool flag = true;
			for (int j = 0; j < parameters.Length; j++)
			{
				if (j < args.Length)
				{
					array[j] = args[j];
					continue;
				}
				if (parameters[j].IsOptional)
				{
					array[j] = parameters[j].DefaultValue;
					continue;
				}
				flag = false;
				break;
			}
			if (flag)
			{
				return methodInfo.Invoke((!methodInfo.IsStatic) ? o : null, array);
			}
		}
		throw new MissingMethodException(o.GetType().Name, name);
	}
}
internal static class Game
{
	public static object Player()
	{
		object o = Rf.Instance("GameNetworkManager");
		object obj = Rf.Get(o, "localPlayerController");
		return (!Rf.Dead(obj)) ? obj : null;
	}

	public static object Round()
	{
		return Rf.Instance("StartOfRound");
	}

	public static bool PlayerInShip()
	{
		return Rf.Bool(Player(), "isInHangarShipRoom", def: false);
	}

	public static bool InOrbit()
	{
		return Rf.Bool(Round(), "inShipPhase", def: true);
	}

	public static bool Landed()
	{
		return Rf.Bool(Round(), "shipHasLanded", def: false);
	}

	public static bool Leaving()
	{
		return Rf.Bool(Round(), "shipIsLeaving", def: false);
	}

	public static bool IsHost()
	{
		object o = Rf.Instance("HUDManager");
		return Rf.Bool(o, "IsServer", def: false);
	}

	public static string MoonName()
	{
		object obj = Rf.Get(Round(), "currentLevel");
		if (obj == null)
		{
			return string.Empty;
		}
		return ((Rf.Get(obj, "PlanetName") as string) ?? string.Empty) + " " + ((Rf.Get(obj, "sceneName") as string) ?? string.Empty);
	}

	public static bool AtCompany()
	{
		object obj = Rf.Get(Round(), "currentLevel");
		if (obj == null)
		{
			return false;
		}
		if (Rf.Int(obj, "levelID", -1) == 3)
		{
			return true;
		}
		return MoonName().IndexOf("Gordion", StringComparison.OrdinalIgnoreCase) >= 0;
	}

	public static bool ExcludedMoon()
	{
		object obj = Rf.Get(Round(), "currentLevel");
		if (obj == null)
		{
			return false;
		}
		if (Rf.Int(obj, "levelID", -1) == 3)
		{
			return true;
		}
		string text = MoonName();
		return text.IndexOf("Gordion", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Galetry", StringComparison.OrdinalIgnoreCase) >= 0;
	}

	public static bool DayMinutes(out float elapsed, out float clock)
	{
		elapsed = (clock = 0f);
		object obj = Rf.Instance("TimeOfDay");
		if (obj == null)
		{
			return false;
		}
		float num = Rf.Float(obj, "currentDayTime", -1f);
		float num2 = Rf.Float(obj, "totalTime", -1f);
		int num3 = Rf.Int(obj, "numberOfHours", -1);
		if (num < 0f || num2 <= 0f || num3 <= 0)
		{
			return false;
		}
		elapsed = num / num2 * 60f * (float)num3;
		clock = elapsed + 360f;
		return true;
	}
}
internal static class QuotaTracker
{
	public static string QuotaLabel = "QUOTA";

	public static string OvertimeLabel = "OVERTIME";

	public static bool AutoDisplay = true;

	public static float OffsetX;

	public static float OffsetY;

	public static bool QuotaTextHas;

	public static bool QuotaLineHas;

	public static bool OvertimeTextHas;

	public static bool OvertimeLineHas;

	public static float QuotaTextR;

	public static float QuotaTextG;

	public static float QuotaTextB;

	public static float QuotaLineR;

	public static float QuotaLineG;

	public static float QuotaLineB;

	public static float OvertimeTextR;

	public static float OvertimeTextG;

	public static float OvertimeTextB;

	public static float OvertimeLineR;

	public static float OvertimeLineG;

	public static float OvertimeLineB;

	public static Action<string> Info;

	public static Action<string> Warn;

	public static Action ItemsChanged;

	public static bool HideWhenDead;

	private static GameObject _quotaRoot;

	private static GameObject _overtimeRoot;

	private static TextMeshProUGUI _quotaText;

	private static TextMeshProUGUI _overtimeText;

	private static Vector3 _quotaBase;

	private static Vector3 _overtimeBase;

	private static readonly List<GrabbableObject> OnCounter = new List<GrabbableObject>();

	private static readonly Stopwatch Clock = Stopwatch.StartNew();

	private static double _shownUntil;

	private const double ManualSeconds = 8.0;

	private static bool _atCompany;

	private static bool _suppressed;

	private static double _nextRefresh;

	private static double _nextCreate;

	private static double _nextDeskFind;

	private static object _desk;

	private static readonly HashSet<int> Sold = new HashSet<int>();

	private static int _watchAmount;

	private static int _watchFulfilled;

	private static double _watchUntil;

	private static bool _warnedTemplate;

	private static bool _warnedTick;

	private static bool _sourceLogged;

	private static int _fulfilledBefore;

	private static int _pendingBefore;

	private static bool _lastFromGame;

	private static int _lastPending;

	private static int _lastFulfilled;

	private static float _lastRate;

	private static string _lastQuotaText;

	private static string _lastOvertimeText;

	public static List<GameObject> Rows()
	{
		List<GameObject> list = new List<GameObject>();
		if (!Rf.Dead(_quotaRoot))
		{
			list.Add(_quotaRoot);
		}
		if (!Rf.Dead(_overtimeRoot))
		{
			list.Add(_overtimeRoot);
		}
		return list;
	}

	public static void Install(object harmony, MethodInfo patch, Type harmonyMethodType)
	{
		Hook(harmony, patch, harmonyMethodType, "DepositItemsDesk", "Start", null, "AfterStart");
		Hook(harmony, patch, harmonyMethodType, "DepositItemsDesk", "AddObjectToDeskClientRpc", null, "AfterAdd");
		Hook(harmony, patch, harmonyMethodType, "DepositItemsDesk", "SellItemsClientRpc", "BeforeSell", "AfterSell");
		Hook(harmony, patch, harmonyMethodType, "StartOfRound", "EndOfGame", "BeforeDayEnds", null);
		Hook(harmony, patch, harmonyMethodType, "GameNetworkManager", "StartDisconnect", null, "AfterDisconnect");
		Hook(harmony, patch, harmonyMethodType, "HUDManager", "PingScan_performed", null, "AfterRightClick");
	}

	private static void Hook(object harmony, MethodInfo patch, Type hm, string type, string method, string prefix, string postfix)
	{
		try
		{
			Type type2 = Rf.T(type);
			MethodInfo methodInfo = null;
			if (type2 != null)
			{
				MethodInfo[] methods = type2.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo2 in methods)
				{
					if (methodInfo2.Name == method)
					{
						methodInfo = methodInfo2;
						break;
					}
				}
			}
			if (methodInfo == null)
			{
				throw new MissingMethodException(type + "." + method);
			}
			object[] array = new object[patch.GetParameters().Length];
			array[0] = methodInfo;
			if (prefix != null)
			{
				array[1] = Activator.CreateInstance(hm, typeof(QuotaTracker).GetMethod(prefix, BindingFlags.Static | BindingFlags.NonPublic));
			}
			if (postfix != null)
			{
				array[2] = Activator.CreateInstance(hm, typeof(QuotaTracker).GetMethod(postfix, BindingFlags.Static | BindingFlags.NonPublic));
			}
			patch.Invoke(harmony, array);
		}
		catch (Exception ex)
		{
			if (Warn != null)
			{
				Warn("QuotaTracker: could not hook " + type + "." + method + " (" + (ex.InnerException ?? ex).Message + ")");
			}
		}
	}

	private static void AfterStart(object __instance)
	{
		try
		{
			_desk = __instance;
			_suppressed = false;
			_atCompany = true;
			OnCounter.Clear();
			Sold.Clear();
			_watchAmount = 0;
			Create();
			Refresh();
		}
		catch (Exception ex)
		{
			if (Warn != null)
			{
				Warn("QuotaTracker start failed: " + ex.Message);
			}
		}
	}

	private static void AfterAdd(object __instance)
	{
		try
		{
			object obj = Rf.Get(__instance, "lastObjectAddedToDesk");
			Component val = (Component)((obj is Component) ? obj : null);
			GrabbableObject val2 = ((!((Object)(object)val == (Object)null)) ? val.GetComponentInChildren<GrabbableObject>() : null);
			if ((Object)(object)val2 != (Object)null && !OnCounter.Contains(val2))
			{
				OnCounter.Add(val2);
			}
			Refresh();
			if (ItemsChanged != null)
			{
				ItemsChanged();
			}
		}
		catch (Exception ex)
		{
			if (Warn != null)
			{
				Warn("QuotaTracker: item added, but " + ex.Message);
			}
		}
	}

	private static void BeforeSell(object __instance)
	{
		try
		{
			object o = Rf.Instance("TimeOfDay");
			object o2 = Game.Round();
			_fulfilledBefore = Rf.Int(o, "quotaFulfilled", 0);
			int num = 0;
			bool fromGame;
			List<GrabbableObject> list = DeskItems(out fromGame);
			for (int i = 0; i < list.Count; i++)
			{
				Sold.Add(((Object)list[i]).GetInstanceID());
				if ((Object)(object)list[i].itemProperties != (Object)null && list[i].itemProperties.isScrap)
				{
					num += list[i].scrapValue;
				}
			}
			_pendingBefore = (int)((float)num * Rf.Float(o2, "companyBuyingRate", 1f));
		}
		catch (Exception)
		{
			_pendingBefore = 0;
		}
	}

	private static void AfterSell(object __instance)
	{
		try
		{
			object o = Rf.Instance("TimeOfDay");
			int num = Rf.Int(o, "quotaFulfilled", 0);
			if (_pendingBefore > 0 && num == _fulfilledBefore)
			{
				_watchAmount = _pendingBefore;
				_watchFulfilled = num;
				_watchUntil = Clock.Elapsed.TotalSeconds + 8.0;
			}
			_pendingBefore = 0;
			OnCounter.Clear();
			Refresh();
			if (ItemsChanged != null)
			{
				ItemsChanged();
			}
		}
		catch (Exception)
		{
		}
	}

	private static void BeforeDayEnds()
	{
		AutoScan.FireFinal();
		Hide();
		OnCounter.Clear();
		Sold.Clear();
		_watchAmount = 0;
		_atCompany = false;
		_suppressed = true;
	}

	private static void AfterDisconnect()
	{
		AutoScan.EndSession();
		Hide();
		OnCounter.Clear();
		Sold.Clear();
		_watchAmount = 0;
		_atCompany = false;
		_suppressed = true;
	}

	private static void AfterRightClick()
	{
		try
		{
			if (_atCompany && !AutoDisplay)
			{
				_shownUntil = Clock.Elapsed.TotalSeconds + 8.0;
				Refresh();
			}
		}
		catch (Exception)
		{
		}
	}

	public static void Tick()
	{
		try
		{
			double totalSeconds = Clock.Elapsed.TotalSeconds;
			if (Game.InOrbit())
			{
				_suppressed = false;
				if (_atCompany)
				{
					Hide();
					OnCounter.Clear();
					Sold.Clear();
					_atCompany = false;
				}
			}
			else if (!_atCompany && !_suppressed && Game.AtCompany())
			{
				_atCompany = true;
				OnCounter.Clear();
				Sold.Clear();
				if (Info != null)
				{
					Info("QuotaTracker: Company detected from the game state.");
				}
			}
			if (!_atCompany)
			{
				return;
			}
			if (Rf.Dead(_quotaRoot) || Rf.Dead(_overtimeRoot) || (Object)(object)_quotaText == (Object)null || (Object)(object)_overtimeText == (Object)null)
			{
				if (totalSeconds < _nextCreate)
				{
					return;
				}
				_nextCreate = totalSeconds + 1.0;
				Create();
				if (Rf.Dead(_quotaRoot) || Rf.Dead(_overtimeRoot))
				{
					return;
				}
				Refresh();
			}
			bool flag = (AutoDisplay || totalSeconds < _shownUntil) && (!HideWhenDead || !Rf.Bool(Game.Player(), "isPlayerDead", def: false));
			if (_quotaRoot.activeSelf != flag)
			{
				_quotaRoot.SetActive(flag);
				if (!Rf.Dead(_overtimeRoot))
				{
					_overtimeRoot.SetActive(flag);
				}
				if (flag)
				{
					Refresh();
				}
			}
			else if (flag && totalSeconds >= _nextRefresh)
			{
				_nextRefresh = totalSeconds + 0.5;
				Refresh();
			}
		}
		catch (Exception ex)
		{
			if (!_warnedTick && Warn != null)
			{
				_warnedTick = true;
				Warn("QuotaTracker update problem: " + ex.Message);
			}
		}
	}

	private static GameObject FindTemplate()
	{
		GameObject val = GameObject.Find("/Systems/UI/Canvas/IngamePlayerHUD/BottomMiddle/ValueCounter");
		if ((Object)(object)val != (Object)null)
		{
			return val;
		}
		GameObject val2 = GameObject.Find("/Systems");
		if ((Object)(object)val2 == (Object)null)
		{
			return null;
		}
		Transform val3 = val2.transform.Find("UI/Canvas/IngamePlayerHUD/BottomMiddle/ValueCounter");
		return (!((Object)(object)val3 == (Object)null)) ? ((Component)val3).gameObject : null;
	}

	private static void Create()
	{
		if (!Rf.Dead(_quotaRoot) && !Rf.Dead(_overtimeRoot) && (Object)(object)_quotaText != (Object)null && (Object)(object)_overtimeText != (Object)null)
		{
			return;
		}
		GameObject val = FindTemplate();
		if ((Object)(object)val == (Object)null)
		{
			if (!_warnedTemplate && Warn != null)
			{
				_warnedTemplate = true;
				Warn("QuotaTracker: the HUD template (ValueCounter) was not found yet. Trying again every second.");
			}
			return;
		}
		if (!Rf.Dead(_quotaRoot))
		{
			Object.Destroy((Object)(object)_quotaRoot);
		}
		if (!Rf.Dead(_overtimeRoot))
		{
			Object.Destroy((Object)(object)_overtimeRoot);
		}
		_quotaRoot = MakeRow(val, out _quotaText, -70f, out _quotaBase);
		_overtimeRoot = MakeRow(val, out _overtimeText, -90f, out _overtimeBase);
		_warnedTemplate = false;
		if (Info != null)
		{
			Info("QuotaTracker: HUD rows created.");
		}
	}

	private static GameObject MakeRow(GameObject source, out TextMeshProUGUI text, float y, out Vector3 basePos)
	{
		//IL_003a: 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)
		GameObject val = Object.Instantiate<GameObject>(source, source.transform.parent, false);
		val.SetActive(true);
		val.transform.Translate(0f, 1f, 0f);
		Vector3 localPosition = val.transform.localPosition;
		((Vector3)(ref basePos))..ctor(localPosition.x + 50f, y, localPosition.z);
		text = val.GetComponentInChildren<TextMeshProUGUI>();
		return val;
	}

	private static void Hide()
	{
		try
		{
			if (!Rf.Dead(_quotaRoot))
			{
				_quotaRoot.SetActive(false);
			}
			if (!Rf.Dead(_overtimeRoot))
			{
				_overtimeRoot.SetActive(false);
			}
		}
		catch (Exception)
		{
		}
	}

	public static int RealDays(int daysUntilDeadline, float globalTimeAtEndOfDay)
	{
		return (globalTimeAtEndOfDay != 0f) ? (daysUntilDeadline - 1) : daysUntilDeadline;
	}

	public static void Numbers(int fulfilled, int quota, int pendingValue, float buyingRate, int days, out int shownFulfilled, out int overtime)
	{
		int num = (int)((float)pendingValue * buyingRate);
		shownFulfilled = fulfilled + num;
		overtime = 0;
		if (shownFulfilled >= quota)
		{
			long val = ((long)shownFulfilled - (long)quota) / 5 + 15L * (long)days;
			overtime = (int)Math.Max(0L, Math.Min(536870911L, val));
		}
	}

	public static string QuotaLine(string label, int fulfilled, int quota)
	{
		return ((!string.IsNullOrEmpty(label)) ? label : "QUOTA") + ": $" + fulfilled + "/" + quota;
	}

	public static string OvertimeLine(string label, int overtime)
	{
		return ((!string.IsNullOrEmpty(label)) ? label : "OVERTIME") + ": $" + overtime;
	}

	private static List<GrabbableObject> DeskItems(out bool fromGame)
	{
		fromGame = false;
		List<GrabbableObject> list = new List<GrabbableObject>();
		try
		{
			double totalSeconds = Clock.Elapsed.TotalSeconds;
			if (Rf.Dead(_desk))
			{
				_desk = null;
				Type type = Rf.T("DepositItemsDesk");
				if (type != null && totalSeconds >= _nextDeskFind)
				{
					_nextDeskFind = totalSeconds + 2.0;
					Object val = Object.FindObjectOfType(type);
					if (!Rf.Dead(val))
					{
						_desk = val;
					}
				}
			}
			if (Rf.Get(_desk, "itemsOnCounter") is IEnumerable enumerable)
			{
				foreach (object item in enumerable)
				{
					GrabbableObject val2 = (GrabbableObject)((item is GrabbableObject) ? item : null);
					if ((Object)(object)val2 != (Object)null && !Rf.Dead(val2) && !Sold.Contains(((Object)val2).GetInstanceID()))
					{
						list.Add(val2);
					}
				}
				fromGame = true;
				return list;
			}
		}
		catch (Exception)
		{
		}
		OnCounter.RemoveAll((GrabbableObject g) => (Object)(object)g == (Object)null);
		for (int num = 0; num < OnCounter.Count; num++)
		{
			if (!Sold.Contains(((Object)OnCounter[num]).GetInstanceID()))
			{
				list.Add(OnCounter[num]);
			}
		}
		return list;
	}

	public static bool Compute(out int shown, out int quota, out int overtime)
	{
		shown = (quota = (overtime = 0));
		object obj = Rf.Instance("TimeOfDay");
		object obj2 = Game.Round();
		if (obj == null || obj2 == null)
		{
			return false;
		}
		int num = 0;
		bool fromGame;
		List<GrabbableObject> list = DeskItems(out fromGame);
		for (int i = 0; i < list.Count; i++)
		{
			GrabbableObject val = list[i];
			if ((Object)(object)val.itemProperties != (Object)null && val.itemProperties.isScrap)
			{
				num += val.scrapValue;
			}
		}
		if (fromGame && !_sourceLogged)
		{
			_sourceLogged = true;
			if (Info != null)
			{
				Info("QuotaTracker: reading the desk items from the game's own list.");
			}
		}
		quota = Rf.Int(obj, "profitQuota", 0);
		int num2 = Rf.Int(obj, "quotaFulfilled", 0);
		if (_watchAmount > 0)
		{
			if (num2 == _watchFulfilled && Clock.Elapsed.TotalSeconds < _watchUntil)
			{
				num2 += _watchAmount;
			}
			else
			{
				_watchAmount = 0;
			}
		}
		float num3 = Rf.Float(obj2, "companyBuyingRate", 1f);
		_lastFromGame = fromGame;
		_lastPending = num;
		_lastFulfilled = num2;
		_lastRate = num3;
		Numbers(num2, quota, num, num3, RealDays(Rf.Int(obj, "daysUntilDeadline", 1), Rf.Float(obj, "globalTimeAtEndOfDay", 0f)), out shown, out overtime);
		return true;
	}

	public static int OvertimeNow()
	{
		if (!Compute(out var shown, out var quota, out var overtime))
		{
			return -1;
		}
		object o = Rf.Instance("TimeOfDay");
		if (Info != null)
		{
			Info("Overtime check: quota " + quota + ", fulfilled " + _lastFulfilled + ", desk " + _lastPending + " x " + _lastRate + " (" + ((!_lastFromGame) ? "own list" : "game list") + "), shown " + shown + ", daysUntilDeadline " + Rf.Int(o, "daysUntilDeadline", -99) + ", globalTimeAtEndOfDay " + Rf.Float(o, "globalTimeAtEndOfDay", -1f) + ", timeUntilDeadline " + Rf.Float(o, "timeUntilDeadline", -1f) + ", overtime " + overtime);
		}
		return overtime;
	}

	public static void Refresh()
	{
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		if (!Rf.Dead(_quotaRoot) && !Rf.Dead(_overtimeRoot) && !((Object)(object)_quotaText == (Object)null) && !((Object)(object)_overtimeText == (Object)null) && Compute(out var shown, out var quota, out var overtime))
		{
			((TMP_Text)_quotaText).text = QuotaLine(QuotaLabel, shown, quota);
			UltimateStyle.Row(_quotaRoot, (TMP_Text)(object)_quotaText, QuotaTextHas, QuotaTextR, QuotaTextG, QuotaTextB, QuotaLineHas, QuotaLineR, QuotaLineG, QuotaLineB);
			((TMP_Text)_overtimeText).text = OvertimeLine(OvertimeLabel, overtime);
			UltimateStyle.Row(_overtimeRoot, (TMP_Text)(object)_overtimeText, OvertimeTextHas, OvertimeTextR, OvertimeTextG, OvertimeTextB, OvertimeLineHas, OvertimeLineR, OvertimeLineG, OvertimeLineB);
			if (!DeadHud.IsLifted(_quotaRoot))
			{
				_quotaRoot.transform.localPosition = new Vector3(_quotaBase.x + OffsetX, _quotaBase.y + OffsetY, _quotaBase.z);
			}
			if (!DeadHud.IsLifted(_overtimeRoot))
			{
				_overtimeRoot.transform.localPosition = new Vector3(_overtimeBase.x + OffsetX, _overtimeBase.y + OffsetY, _overtimeBase.z);
			}
			bool active = (AutoDisplay || Clock.Elapsed.TotalSeconds < _shownUntil) && (!HideWhenDead || !Rf.Bool(Game.Player(), "isPlayerDead", def: false));
			_quotaRoot.SetActive(active);
			_overtimeRoot.SetActive(active);
		}
	}
}
[BepInPlugin("Crispy_Depression.Ultimate_Scanner", "Ultimate Scanner", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class UltimateScanPlugin : BaseUnityPlugin
{
	private enum Mode
	{
		Normal,
		Rainbow,
		Rgb,
		Negative,
		Fire,
		Ocean,
		Neon,
		Sunset,
		Toxic,
		Ice,
		Gold,
		Disco
	}

	private class ColorCfg
	{
		public bool Has;

		public float R;

		public float G;

		public float B;
	}

	private class ColorPair
	{
		public ConfigEntry<string> Entry;

		public string Section;

		public string Key;

		public string OldLineKey;

		public ColorCfg Text = new ColorCfg();

		public ColorCfg Line = new ColorCfg();
	}

	private sealed class RowAccess
	{
		public Func<int> Count;

		public Action<int, float, float, float> SetEnv;
	}

	public const string PluginGuid = "Crispy_Depression.Ultimate_Scanner";

	public const string PluginName = "Ultimate Scanner";

	public const string PluginVersion = "1.0.0";

	private const string Default = "#00F2E6";

	private const string ColorHelp = "Hex color, e.g. FF4040. Empty = game default.";

	private const BindingFlags AnyStatic = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

	private const BindingFlags AnyInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

	private static readonly string[] ModeNames = new string[14]
	{
		"Normal", "Rainbow", "RGB", "Negative", "Fire", "Ocean", "Neon", "Sunset", "Toxic", "Ice",
		"Gold", "Disco", "Random", "TrueRandom"
	};

	private ConfigEntry<string> _modeEntry;

	private ConfigEntry<float> _speed;

	private ConfigEntry<bool> _logTiming;

	private ConfigEntry<bool> _shipAnywhere;

	private ConfigEntry<bool> _debugCycle;

	private ConfigEntry<string> _cruiserFormat;

	private ConfigEntry<string> _labels;

	private ConfigEntry<string> _shipFormat;

	private ConfigEntry<string> _cruiserOffset;

	private ConfigEntry<string> _quotaOffset;

	private ConfigEntry<string> _shipOffset;

	private ConfigEntry<float> _shipCache;

	private ConfigEntry<float> _displayTime;

	private ConfigEntry<float> _autoSec;

	private ConfigEntry<bool> _autoDisplay;

	private ConfigEntry<bool> _deadDisplay;

	private ConfigEntry<bool> _chatScan;

	private ConfigEntry<bool> _cruiserChat;

	private ConfigEntry<bool> _dayStart;

	private ConfigEntry<bool> _scanBodies;

	private ConfigEntry<bool> _finalScan;

	private ConfigEntry<string> _finalFormat;

	private ConfigEntry<string> _interval;

	private ConfigEntry<string> _cruiserInterval;

	private ConfigEntry<string> _scanFormat;

	private ConfigEntry<string> _cruiserScanFormat;

	private ConfigEntry<string> _announceColor;

	private ConfigEntry<float> _dayDelay;

	private ColorCfg _cruiserText;

	private ColorCfg _cruiserLine;

	private ColorCfg _countText;

	private ColorCfg _countLine;

	private ColorCfg _quotaText;

	private ColorCfg _quotaLine;

	private ColorCfg _overtimeText;

	private ColorCfg _overtimeLine;

	private ColorCfg _shipText;

	private ColorCfg _shipLine;

	private readonly List<ColorPair> _pairs = new List<ColorPair>();

	private Mode _mode;

	private const string PairHelp = "Text color, line color, e.g. #00F2E6, #00F2E6. Only 1 color = used for both text and line. Empty = game default.";

	internal const string SecCruiser = "1 CruiserScrapCounter";

	internal const string SecQuota = "2 UiSellTracker";

	internal const string SecShip = "3 ShipLootCruiser";

	internal const string SecShipGeneral = "3 ShipLootCruiser General";

	internal const string SecAuto = "AutoTerminalScan";

	internal const string SecShared = "0 Shared Config All Mods";

	private static UltimateScanPlugin _self;

	private Assembly _asmCruiser;

	private Assembly _asmShip;

	private static object _hiddenConfig;

	private volatile bool _changed;

	private volatile bool _hookInstalled;

	private Mode _lastApplied = (Mode)(-1);

	private int _trueIdx = -1;

	private int _debugIdx = -1;

	private bool _pickNew;

	private double _nextResolve;

	private readonly Random _rng = new Random();

	private double _lastPick = -10.0;

	private Func<bool> _scanPressed;

	private double _nextScanLookup;

	private string _scanInputName = string.Empty;

	private List<RowAccess> _rowAccess;

	private static readonly float[][] FireStops = new float[4][]
	{
		new float[3] { 0.85f, 0.1f, 0f },
		new float[3] { 1f, 0.45f, 0f },
		new float[3] { 1f, 0.8f, 0.1f },
		new float[3] { 1f, 0.4f, 0f }
	};

	private static readonly float[][] OceanStops = new float[4][]
	{
		new float[3] { 0f, 0.25f, 0.9f },
		new float[3] { 0f, 0.7f, 1f },
		new float[3] { 0f, 0.95f, 0.85f },
		new float[3] { 0.1f, 0.5f, 0.9f }
	};

	private static readonly float[][] NeonStops = new float[4][]
	{
		new float[3] { 1f, 0.05f, 0.65f },
		new float[3] { 0.55f, 0.1f, 1f },
		new float[3] { 0f, 0.95f, 1f },
		new float[3] { 0.1f, 1f, 0.5f }
	};

	private static readonly float[][] SunsetStops = new float[4][]
	{
		new float[3] { 0.55f, 0.15f, 0.75f },
		new float[3] { 1f, 0.3f, 0.4f },
		new float[3] { 1f, 0.6f, 0.15f },
		new float[3] { 1f, 0.85f, 0.45f }
	};

	private static readonly float[][] ToxicStops = new float[3][]
	{
		new float[3] { 0.55f, 1f, 0f },
		new float[3] { 0.1f, 0.9f, 0.1f },
		new float[3] { 0.85f, 1f, 0.1f }
	};

	private static readonly float[][] IceStops = new float[4][]
	{
		new float[3] { 1f, 1f, 1f },
		new float[3] { 0.65f, 0.9f, 1f },
		new float[3] { 0.3f, 0.7f, 1f },
		new float[3] { 0.85f, 0.97f, 1f }
	};

	private static readonly float[][] GoldStops = new float[4][]
	{
		new float[3] { 1f, 0.75f, 0.1f },
		new float[3] { 1f, 0.9f, 0.45f },
		new float[3] { 0.85f, 0.6f, 0.05f },
		new float[3] { 1f, 0.95f, 0.7f }
	};

	private object _cruiserDisplayTime;

	private object _cruiserOffX;

	private object _cruiserOffY;

	private object _shipDisplayTime;

	private bool _quotaInstallPending;

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

	private bool _frameBroken;

	private int _autoFrame = -1;

	private double _nextCruiserAuto;

	private double _nextShipAuto;

	private static readonly Stopwatch Clock = Stopwatch.StartNew();

	private bool _autoWarnCruiser;

	private bool _autoWarnShip;

	private MethodInfo _cruiserPostfix;

	private MethodInfo _shipRefresh;

	private bool _deadLogged;

	private bool _deadShipOk;

	private bool _deadCruiserOk;

	private bool _debugWarned;

	private volatile bool _dirty;

	private double _recheckAt;

	private double _lastEventRefresh;

	private double _eventTime;

	private int _recheckStage;

	private double _nextPoll;

	private int _lastPlayerState = -1;

	private double _nextDeadHud;

	private bool _envBroken;

	private Texture2D _probe;

	private readonly Dictionary<string, Color> _envSmooth = new Dictionary<string, Color>();

	private FileSystemWatcher _watcher;

	private Timer _debounce;

	private void BindPair(string section, string key, string oldLineKey, out ColorCfg text, out ColorCfg line)
	{
		ColorPair colorPair = new ColorPair();
		colorPair.Section = section;
		colorPair.Key = key;
		colorPair.OldLineKey = oldLineKey;
		ColorPair colorPair2 = colorPair;
		colorPair2.Entry = ((BaseUnityPlugin)this).Config.Bind<string>(section, key, "#00F2E6, #00F2E6", "Text color, line color, e.g. #00F2E6, #00F2E6. Only 1 color = used for both text and line. Empty = game default.");
		Subscribe(colorPair2.Entry);
		_pairs.Add(colorPair2);
		text = colorPair2.Text;
		line = colorPair2.Line;
	}

	private static void Split2(string v, string second, out string a, out string b)
	{
		v = v ?? string.Empty;
		int num = v.IndexOf(',');
		if (num < 0)
		{
			a = v.Trim();
			b = second ?? a;
		}
		else
		{
			a = v.Substring(0, num).Trim();
			b = v.Substring(num + 1).Trim();
		}
	}

	private ConfigEntry<T> Watch<T>(ConfigEntry<T> e)
	{
		Subscribe(e);
		return e;
	}

	private void Subscribe(object entry)
	{
		try
		{
			EventInfo eventInfo = entry.GetType().GetEvent("SettingChanged", BindingFlags.Instance | BindingFlags.Public);
			if (eventInfo != null)
			{
				eventInfo.AddEventHandler(entry, new EventHandler(OnSettingChanged));
			}
		}
		catch (Exception)
		{
		}
	}

	private void BindConfig()
	{
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Expected O, but got Unknown
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Expected O, but got Unknown
		//IL_031b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0325: Expected O, but got Unknown
		_displayTime = Watch<float>(((BaseUnityPlugin)this).Config.Bind<float>("0 Shared Config All Mods", "Display Time", 10f, new ConfigDescription("How long each HUD stays on screen after it is shown, in seconds (all three mods).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 30f), Array.Empty<object>())));
		_autoDisplay = Watch<bool>(((BaseUnityPlugin)this).Config.Bind<bool>("0 Shared Config All Mods", "AutoDisplay", true, "HUDs show by themselves: ship total in the ship, Cruiser counter outside on a moon, quota at the Company. Off = right-click only."));
		_autoSec = Watch<float>(((BaseUnityPlugin)this).Config.Bind<float>("0 Shared Config All Mods", "AutoDisplay Interval", 1f, new ConfigDescription("Backup refresh in seconds. HUDs already update the moment loot moves.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), Array.Empty<object>())));
		_scanBodies = Watch<bool>(((BaseUnityPlugin)this).Config.Bind<bool>("0 Shared Config All Mods", "Scan Bodies", false, "Count player bodies in every scan and HUD (/scan, /scan -c, chat scans, Cruiser counter, ship total). Off = bodies are never counted."));
		_deadDisplay = Watch<bool>(((BaseUnityPlugin)this).Config.Bind<bool>("0 Shared Config All Mods", "DeadDisplay", true, "While dead, keep showing the HUDs: ship total + Cruiser counter on a moon, ship total + quota at the Company."));
		_cruiserFormat = ((BaseUnityPlugin)this).Config.Bind<string>("1 CruiserScrapCounter", "Format", "Cruiser: {0}/{1}\\nCount:   {2}/{3}", "{0} cruiser value, {1} moon value, {2} cruiser items, {3} moon items. \\n = new line.");
		BindPair("1 CruiserScrapCounter", "Cruiser Color", "Cruiser Line Color", out _cruiserText, out _cruiserLine);
		BindPair("1 CruiserScrapCounter", "Count Color", "Count Line Color", out _countText, out _countLine);
		_cruiserOffset = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("1 CruiserScrapCounter", "Offset", "0, 0", "Move the text: x, y (+x = right, +y = up). Example: 0, 0"));
		_labels = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("2 UiSellTracker", "Labels", "QUOTA, OVERTIME", "Names before the quota and before the overtime, separated by a comma."));
		BindPair("2 UiSellTracker", "Quota Color", "Quota Line Color", out _quotaText, out _quotaLine);
		BindPair("2 UiSellTracker", "Overtime Color", "Overtime Line Color", out _overtimeText, out _overtimeLine);
		_quotaOffset = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("2 UiSellTracker", "Offset", "0, 0", "Move the text: x, y (+x = right, +y = up). Example: 0, 0"));
		_shipFormat = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("3 ShipLootCruiser", "Format", "SHIP:${value}({count})", "{value} ship value, {count} item count. \\n = new line."));
		BindPair("3 ShipLootCruiser", "Color", "Line Color", out _shipText, out _shipLine);
		_shipAnywhere = Watch<bool>(((BaseUnityPlugin)this).Config.Bind<bool>("3 ShipLootCruiser", "Show Anywhere", false, "Show the ship total from anywhere, not only in the ship."));
		_shipCache = Watch<float>(((BaseUnityPlugin)this).Config.Bind<float>("3 ShipLootCruiser", "Cache Seconds", 0f, "Reuse the last count for this many seconds (0 = always recount)."));
		_shipOffset = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("3 ShipLootCruiser", "Offset", "0, 0", "Move the text: x, y (+x = right, +y = up). Example: 0, 0"));
		_modeEntry = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("3 ShipLootCruiser General", "Color Mode", "Rainbow", new ConfigDescription("Normal = your colors. Negative = opposite of the screen. Random = new mode every day. TrueRandom = new mode every right-click. The rest are animated.", (AcceptableValueBase)(object)new AcceptableValueList<string>(ModeNames), Array.Empty<object>())));
		_speed = Watch<float>(((BaseUnityPlugin)this).Config.Bind<float>("3 ShipLootCruiser General", "Rainbow Speed", 1f, "Speed of the animated modes (color cycles per second)."));
		_logTiming = Watch<bool>(((BaseUnityPlugin)this).Config.Bind<bool>("3 ShipLootCruiser General", "Log Scan Time", false, "Log how long each ship scan takes."));
		_debugCycle = Watch<bool>(((BaseUnityPlugin)this).Config.Bind<bool>("3 ShipLootCruiser General", "Debug Color Cycle", false, "Debug: each right-click shows the next color mode (chat says which)."));
		_chatScan = Watch<bool>(((BaseUnityPlugin)this).Config.Bind<bool>("AutoTerminalScan", "ChatAutoScan", false, "Send the scan to everyone's chat on the Interval Scan schedule."));
		_interval = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("AutoTerminalScan", "Interval Scan", "1", "In-game times (7am, 8pm) and/or hours between scans (2 = every 2 hours). Comma separated."));
		_cruiserChat = Watch<bool>(((BaseUnityPlugin)this).Config.Bind<bool>("AutoTerminalScan", "AutoCruiserScan", false, "Send the Cruiser counter to everyone's chat on the Cruiser Interval Scan schedule."));
		_finalScan = Watch<bool>(((BaseUnityPlugin)this).Config.Bind<bool>("AutoTerminalScan", "FinalScan", true, "Send the final stats to chat when the ship starts leaving (lever or autopilot). /finalscan turns it off or on for one game only."));
		_finalFormat = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("AutoTerminalScan", "FinalScan Format", "<nobr>Collected: {collectedamount}/{totalamount}</nobr> <nobr>Value: {collectedvalue}/{totalvalue}</nobr>", "Final stats message, only loot of this moon. Collected = put in the ship today (and in a Cruiser magneted to it). <nobr> keeps a part on one line."));
		_cruiserInterval = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("AutoTerminalScan", "Cruiser Interval Scan", "1", "Same as Interval Scan, for the Cruiser scan. 1 = every hour."));
		_dayStart = Watch<bool>(((BaseUnityPlugin)this).Config.Bind<bool>("AutoTerminalScan", "AutoTerminalScanDayStart", true, "One scan at the start of every day. Host: to everyone's chat. Client: to your own chat."));
		_dayDelay = Watch<float>(((BaseUnityPlugin)this).Config.Bind<float>("AutoTerminalScan", "DayStartDelay", 2.5f, "Seconds after the ship doors open until the day-start scan. It also waits for the ship to land (values are final then)."));
		_scanFormat = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("AutoTerminalScan", "Scan Format", "In/Out:{insideamount}/{outsideamount} Value:{insidevalue}/{outsidevalue}", "{insideamount} {outsideamount} {insidevalue} {outsidevalue} = scrap inside / outside the facility. Ship and Cruiser loot is not counted."));
		_cruiserScanFormat = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("AutoTerminalScan", "Cruiser Scan Format", "Cruiser:{insidecruiseramount}/{totalinterior} Count:{Cruiseramount}/{TotalinteriorCount}", "{insidecruiseramount} {totalinterior} {Cruiseramount} {TotalinteriorCount} = Cruiser value, moon value, Cruiser items, moon items."));
		_announceColor = Watch<string>(((BaseUnityPlugin)this).Config.Bind<string>("AutoTerminalScan", "Announce Color", "#FFFF00", "Color of the chat messages, hex e.g. FFFF00. Empty = chat default."));
	}

	private void Awake()
	{
		_self = this;
		MigrateOldFile();
		BindConfig();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Ultimate Scanner v1.0.0 loading...");
		_asmCruiser = LoadEmbedded("CruiserScrapCounter", "CruiserScrapCounter.Plugin", "CruiserScrapCounter");
		InstallQuotaTracker();
		_asmShip = LoadEmbedded("ShipLootCruiser", "ShipLootCruiser.ShipLootCruiser", "OreoM.ShipLootCruiser");
		FindModEntries();
		try
		{
			ChatCmds.Register();
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("/scan commands could not be registered: " + ex.Message));
		}
		MigrateOldConfig();
		if (_interval.Value == "12pm, 6pm, 10pm")
		{
			_interval.Value = (string)((ConfigEntryBase)_interval).DefaultValue;
		}
		if (_finalFormat.Value == "Collected: {collectedamount}/{totalamount}\nValue: {collectedvalue}/{totalvalue}")
		{
			_finalFormat.Value = (string)((ConfigEntryBase)_finalFormat).DefaultValue;
		}
		if (_autoSec.Value == 5f || _autoSec.Value == 0.5f || _autoSec.Value < 0.5f)
		{
			_autoSec.Value = (float)((ConfigEntryBase)_autoSec).DefaultValue;
		}
		if (_scanFormat.Value == "Count:{insideamount}/{outsideamount} Value:{insidevalue}/{outsidevalue}")
		{
			_scanFormat.Value = (string)((ConfigEntryBase)_scanFormat).DefaultValue;
		}
		AutoScan.Info = delegate(string m)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)m);
		};
		AutoScan.Warn = delegate(string m)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)m);
		};
		AutoScan.CruiserAsm = _asmCruiser;
		Reconfigure();
		InstallAnimationHooks();
		try
		{
			((MonoBehaviour)this).StartCoroutine(SampleLoop());
		}
		catch (Exception ex2)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Negative mode sampling is unavailable: " + ex2.Message));
		}
		SelfCheck();
		WatchConfigFile();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Ultimate Scanner finished loading.");
	}

	private void MigrateOldFile()
	{
		try
		{
			string configFilePath = ((BaseUnityPlugin)this).Config.ConfigFilePath;
			string directoryName = Path.GetDirectoryName(configFilePath);
			if (File.Exists(configFilePath) && new FileInfo(configFilePath).Length > 0)
			{
				return;
			}
			string[] array = new string[3] { "Crispy_Depression.Ultimate Scanner.cfg", "Crispy_Depression.UltimateScan.cfg", "UltimateScan.cfg" };
			for (int i = 0; i < array.Length; i++)
			{
				string text = Path.Combine(directoryName, array[i]);
				if (File.Exists(text))
				{
					File.Copy(text, configFilePath, overwrite: true);
					((BaseUnityPlugin)this).Config.Reload();
					string text2 = text + ".old";
					if (File.Exists(text2))
					{
						File.Delete(text2);
					}
					File.Move(text, text2);
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Settings copied from " + array[i] + " to " + Path.GetFileName(configFilePath) + " (the old file is now " + array[i] + ".old)."));
					break;
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not copy the old settings file: " + ex.Message));
		}
	}

	private void MigrateOldConfig()
	{
		try
		{
			object value = ((object)((BaseUnityPlugin)this).Config).GetType().GetProperty("OrphanedEntries", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetValue(((BaseUnityPlugin)this).Config, null);
			if (!(value is IDictionary { Count: not 0 } dictionary))
			{
				return;
			}
			Type type = ((object)((BaseUnityPlugin)this).Config).GetType().Assembly.GetType("BepInEx.Configuration.ConfigDefinition");
			PropertyInfo property = type.GetProperty("Section");
			PropertyInfo property2 = type.GetProperty("Key");
			MethodInfo method = ((object)((BaseUnityPlugin)this).Config).GetType().GetMethod("get_Item", new Type[1] { type });
			int num = 0;
			foreach (DictionaryEntry item in dictionary)
			{
				string[][] array = new string[5][]
				{
					new string[2] { "2 ", "2 UiSellTracker" },
					new string[2] { "General", "3 ShipLootCruiser General" },
					new string[2] { "AutoTerminalScan (NEW)", "AutoTerminalScan" },
					new string[2] { "0 Shared", "0 Shared Config All Mods" },
					new string[2] { "AutoTerminalScan", "0 Shared Config All Mods" }
				};
				foreach (string[] array2 in array)
				{
					string text = (string)property.GetValue(item.Key, null);
					bool num2;
					if (array2[0] == "2 ")
					{
						if (!text.StartsWith("2 "))
						{
							continue;
						}
						num2 = text != "2 UiSellTracker";
					}
					else
					{
						num2 = text == array2[0];
					}
					if (num2)
					{
						try
						{
							object obj = method.Invoke(((BaseUnityPlugin)this).Config, new object[1] { Activator.CreateInstance(type, array2[1], (string)property2.GetValue(item.Key, null)) });
							obj.GetType().GetMethod("SetSerializedValue").Invoke(obj, new object[1] { (string)item.Value });
							num++;
						}
						catch (Exception)
						{
						}
					}
				}
			}
			foreach (DictionaryEntry item2 in dictionary)
			{
				if ((string)property2.GetValue(item2.Key, null) == "AutoDisplay" && (string)property.GetValue(item2.Key, null) != "0 Shared Config All Mods" && string.Equals((string)item2.Value, "false", StringComparison.OrdinalIgnoreCase) && _autoDisplay.Value)
				{
					_autoDisplay.Value = false;
					num++;
				}
			}
			foreach (ColorPair pair in _pairs)
			{
				string text2 = null;
				foreach (DictionaryEntry item3 in dictionary)
				{
					if (OldSection((string)property.GetValue(item3.Key, null), pair.Section) && (string)property2.GetValue(item3.Key, null) == pair.OldLineKey)
					{
						text2 = (string)item3.Value;
					}
				}
				if (text2 != null && pair.Entry.Value.IndexOf(',') < 0)
				{
					pair.Entry.Value = pair.Entry.Value.Trim() + ", " + text2.Trim();
					num++;
				}
			}
			string text3 = null;
			string text4 = null;
			foreach (DictionaryEntry item4 in dictionary)
			{
				if (OldSection((string)property.GetValue(item4.Key, null), "2 UiSellTracker"))
				{
					string text5 = (string)property2.GetValue(item4.Key, null);
					if (text5 == "Quota Label")
					{
						text3 = (string)item4.Value;
					}
					else if (text5 == "Overtime Label")
					{
						text4 = (string)item4.Value;
					}
				}
			}
			if ((text3 != null || text4 != null) && _labels.Value == "QUOTA, OVERTIME")
			{
				_labels.Value = (text3 ?? "QUOTA") + ", " + (text4 ?? "OVERTIME");
				num++;
			}
			string[][] array3 = new string[3][]
			{
				new string[1] { "1 CruiserScrapCounter" },
				new string[1] { "2 UiSellTracker" },
				new string[1] { "3 ShipLootCruiser" }
			};
			foreach (string[] array4 in array3)
			{
				float num3 = 0f;
				float num4 = 0f;
				foreach (DictionaryEntry item5 in dictionary)
				{
					string text6 = (string)property.GetValue(item5.Key, null);
					if ((!(array4[0] == "2 UiSellTracker")) ? (text6 != array4[0]) : (!text6.StartsWith("2 ")))
					{
						continue;
					}
					string text7 = (string)property2.GetValue(item5.Key, null);
					if (float.TryParse((string)item5.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
					{
						if (text7 == "Offset X")
						{
							num3 = result;
						}
						else if (text7 == "Offset Y")
						{
							num4 = result;
						}
					}
				}
				ConfigEntry<string> val = ((array4[0] == "1 CruiserScrapCounter") ? _cruiserOffset : ((!(array4[0] == "2 UiSellTracker")) ? _shipOffset : _quotaOffset));
				if ((num3 != 0f || num4 != 0f) && val.Value == "0, 0")
				{
					val.Value = num3.ToString(CultureInfo.InvariantCulture) + ", " + num4.ToString(CultureInfo.InvariantCulture);
					num++;
				}
			}
			dictionary.Clear();
			((object)((BaseUnityPlugin)this).Config).GetType().GetMethod("Save").Invoke(((BaseUnityPlugin)this).Config, null);
			try
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Old settings were migrated (" + num + " kept); removed settings were deleted from the file."));
			}
			catch (Exception)
			{
			}
		}
		catch (Exception ex3)
		{
			try
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not clean up the old config: " + ex3.Message));
			}
			catch (Exception)
			{
				Console.WriteLine("MIG " + ex3);
			}
		}
	}

	private static bool OldSection(string found, string section)
	{
		return (!(section == "2 UiSellTracker")) ? (found == section) : found.StartsWith("2 ");
	}

	private Assembly LoadEmbedded(string display, string pluginTypeName, string originalGuid)
	{
		try
		{
			if (!SwitchOffOriginal(display, originalGuid))
			{
				return null;
			}
			byte[] rawAssembly;
			using (Stream stream = typeof(UltimateScanPlugin).Assembly.GetManifestResourceStream("UltimateScan." + display + ".dll"))
			{
				if (stream == null)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Embedded " + display + " is missing from Ultimate Scanner.dll."));
					return null;
				}
				MemoryStream memoryStream = new MemoryStream();
				stream.CopyTo(memoryStream);
				rawAssembly = memoryStream.ToArray();
			}
			Assembly assembly = Assembly.Load(rawAssembly);
			ShareConfig(assembly);
			Type type = assembly.GetType(pluginTypeName);
			if (type == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)(display + ": plugin class " + pluginTypeName + " not found."));
				return null;
			}
			((Component)this).gameObject.AddComponent(type);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Loaded " + display + "."));
			return assembly;
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Failed to load " + display + ": " + ex));
			return null;
		}
	}

	private bool SwitchOffOriginal(string display, string guid)
	{
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: Expected O, but got Unknown
		if (!Chainloader.PluginInfos.TryGetValue(guid, out var value))
		{
			return true;
		}
		try
		{
			if (string.IsNullOrEmpty(guid))
			{
				return false;
			}
			Type type = Type.GetType("HarmonyLib.Harmony, 0Harmony");
			object obj = Activator.CreateInstance(type, "UltimateScan.Cleanup");
			MethodInfo methodInfo = null;
			MethodInfo[] methods = type.GetMethods();
			foreach (MethodInfo methodInfo2 in methods)
			{
				ParameterInfo[] parameters = methodInfo2.GetParameters();
				if (methodInfo2.Name == "UnpatchAll" && parameters.Length == 1 && parameters[0].ParameterType == typeof(string))
				{
					methodInfo = methodInfo2;
					break;
				}
			}
			if (methodInfo == null)
			{
				throw new MissingMethodException("Harmony.UnpatchAll(string)");
			}
			methodInfo.Invoke(obj, new object[1] { guid });
			PropertyInfo property = ((object)value).GetType().GetProperty("Instance");
			object obj2 = ((!(property == null)) ? property.GetValue(value, null) : null);
			if (obj2 != null)
			{
				Object.Destroy((Object)obj2);
			}
			((BaseUnityPlugin)this).Logger.LogWarning((object)("The original " + display + " is installed. It was switched off and Ultimate Scanner's own copy is used instead (you can remove the original from your profile)."));
			return true;
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("The original " + display + " is installed and could not be switched off (" + ex.Message + "). Remove it from your profile. " + display + " inside Ultimate Scanner was NOT loaded."));
			return false;
		}
	}

	private void ShareConfig(Assembly asm)
	{
		Type type = asm.GetType("UltimateScan.Shim");
		if (type == null)
		{
			return;
		}
		if (_hiddenConfig == null)
		{
			_hiddenConfig = Activator.CreateInstance(typeof(ConfigFile), Path.Combine(Path.GetTempPath(), "Ultimate Scanner.internal.cfg"), false);
			PropertyInfo property = typeof(ConfigFile).GetProperty("SaveOnConfigSet");
			if (property != null)
			{
				property.SetValue(_hiddenConfig, false, null);
			}
		}
		type.GetField("Shared").SetValue(null, ((BaseUnityPlugin)this).Config);
		type.GetField("Hidden").SetValue(null, _hiddenConfig);
	}

	private void OnSettingChanged(object sender, EventArgs e)
	{
		_changed = true;
	}

	private void Reconfigure()
	{
		_changed = false;
		try
		{
			foreach (ColorPair pair in _pairs)
			{
				Split2(pair.Entry.Value, null, out var a, out var b);
				pair.Text.Has = TryParseColor(a, out pair.Text.R, out pair.Text.G, out pair.Text.B);
				pair.Line.Has = TryParseColor(b, out pair.Line.R, out pair.Line.G, out pair.Line.B);
			}
			if (_asmCruiser != null)
			{
				ConfigureCruiser(_asmCruiser);
			}
			ConfigureQuota();
			ConfigureAuto();
			if (_asmShip != null)
			{
				ConfigureShip(_asmShip);
			}
			PushShared();
			ApplyMode(Resolve(), force: true);
			if (_debugCycle.Value && !_debugWarned)
			{
				_debugWarned = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Debug Color Cycle is ON: DeadDisplay is paused. Right-click to step through the color modes.");
			}
			if (!_debugCycle.Value)
			{
				_debugWarned = false;
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Reconfigure failed: " + ex));
		}
	}

	private static bool IsCustom(Mode m)
	{
		return m >= Mode.Fire;
	}

	private static Mode[] Pool()
	{
		Mode[] array = (Mode[])Enum.GetValues(typeof(Mode));
		List<Mode> list = new List<Mode>();
		Mode[] array2 = array;
		foreach (Mode mode in array2)
		{
			if (mode != Mode.Normal)
			{
				list.Add(mode);
			}
		}
		return list.ToArray();
	}

	private Mode Resolve()
	{
		if (_debugCycle != null && _debugCycle.Value)
		{
			Mode[] array = DebugOrder();
			if (_pickNew)
			{
				_debugIdx = (_debugIdx + 1) % array.Length;
				_pickNew = false;
				AnnounceDebug(array[_debugIdx], _debugIdx + 1, array.Length);
			}
			return array[Math.Max(0, _debugIdx)];
		}
		string text = (_modeEntry.Value ?? string.Empty).Trim();
		if (string.Equals(text, "Random", StringComparison.OrdinalIgnoreCase))
		{
			Mode[] array2 = Pool();
			int num = Rf.Int(Game.Round(), "randomMapSeed", DateTime.Now.DayOfYear);
			return array2[new Random(num * 31 + 7).Next(array2.Length)];
		}
		if (string.Equals(text, "TrueRandom", StringComparison.OrdinalIgnoreCase))
		{
			Mode[] array3 = Pool();
			if (_trueIdx < 0 || _pickNew)
			{
				_trueIdx = _rng.Next(array3.Length);
				_pickNew = false;
			}
			return array3[_trueIdx % array3.Length];
		}
		Mode[] array4 = (Mode[])Enum.GetValues(typeof(Mode));
		for (int i = 0; i < array4.Length; i++)
		{
			Mode result = array4[i];
			if (string.Equals(result.ToString(), text, StringComparison.OrdinalIgnoreCase))
			{
				return result;
			}
		}
		return Mode.Normal;
	}

	private void ApplyMode(Mode m, bool force)
	{
		if (!force && m == _lastApplied)
		{
			return;
		}
		_lastApplied = m;
		_mode = m;
		int num = (int)((!IsCustom(m)) ? m : Mode.Negative);
		Assembly[] array = new Assembly[2] { _asmCruiser, _asmShip };
		foreach (Assembly assembly in array)
		{
			if (assembly == null)
			{
				continue;
			}
			try
			{
				Type type = assembly.GetType("UltimateScan.Util");
				Set(type, "Mode", num);
				Set(type, "Speed", _speed.Value);
				if (m != Mode.Negative && !IsCustom(m))
				{
					type.GetMethod("ClearEnv").Invoke(null, null);
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Could not set the color mode: " + ex));
			}
		}
		UltimateStyle.Mode = num;
		UltimateStyle.Speed = _speed.Value;
		if (m != Mode.Negative && !IsCustom(m))
		{
			UltimateStyle.ClearEnv();
		}
	}

	private static void AfterLootMoved(object __instance)
	{
		CruiserWatch.Add(__instance, Clock.Elapsed.TotalSeconds);
		MarkDirty();
	}

	private static Mode[] DebugOrder()
	{
		List<Mode> list = new List<Mode>(Pool());
		list.Add(Mode.Normal);
		return list.ToArray();
	}

	private void AnnounceDebug(Mode m, int number, int total)
	{
		string text = "Color mode " + number + "/" + total + ": " + ((m != Mode.Rgb) ? m.ToString() : "RGB");
		try
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Debug Color Cycle - " + text));
		}
		catch (Exception)
		{
		}
		try
		{
			Rf.Call(Rf.Instance("HUDManager"), "AddChatMessage", "<color=#FFFF00>" + text + "</color>");
		}
		catch (Exception)
		{
		}
	}

	private static void AfterRightClick()
	{
		UltimateScanPlugin self = _self;
		if ((Object)(object)self != (Object)null)
		{
			self.RequestNextMode("hook");
		}
	}

	internal void RequestNextMode(string source)
	{
		if (_debugCycle.Value || string.Equals(_modeEntry.Value, "TrueRandom", StringComparison.OrdinalIgnoreCase))
		{
			double totalSeconds = Clock.Elapsed.TotalSeconds;
			if (!(totalSeconds - _lastPick < 0.25))
			{
				_lastPick = totalSeconds;
				_pickNew = true;
			}
		}
	}

	private void PollScanButton(double now)
	{
		if (!_debugCycle.Value && !string.Equals(_modeEntry.Value, "TrueRandom", StringComparison.OrdinalIgnoreCase))
		{
			return;
		}
		if (_scanPressed == null)
		{
			if (now < _nextScanLookup)
			{
				return;
			}
			_nextScanLookup = now + 2.0;
			_scanPressed = FindScanInput();
			if (_scanPressed == null)
			{
				return;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Right-click detection also watches: " + _scanInputName));
		}
		try
		{
			if (_scanPressed())
			{
				RequestNextMode("button");
			}
		}
		catch (Exception)
		{
			_scanPressed = null;
		}
	}

	private Func<bool> FindScanInput()
	{
		try
		{
			object o = Rf.Instance("IngamePlayerSettings");
			object obj = Rf.Get(Rf.Get(o, "playerInput"), "actions");
			if (obj != null)
			{
				MethodInfo method = obj.GetType().GetMethod("FindAction", new Type[2]
				{
					typeof(string),
					typeof(bool)
				});
				object obj2 = ((!(method == null)) ? method.Invoke(obj, new object[2] { "PingScan", false }) : null);
				MethodInfo methodInfo = obj2?.GetType().GetMethod("WasPerformedThisFrame", Type.EmptyTypes);
				if (methodInfo != null)
				{
					_scanInputName = "input action PingScan";
					return (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), obj2, methodInfo);
				}
			}
		}
		catch (Exception)
		{
		}
		try
		{
			Type type = Type.GetType("UnityEngine.InputSystem.Mouse, Unity.InputSystem");
			object obj3 = ((!(type == null)) ? type.GetProperty("current", BindingFlags.Static | BindingFlags.Public).GetValue(null, null) : null);
			object obj4 = obj3?.GetType().GetProperty("rightButton").GetValue(obj3, null);
			MethodInfo methodInfo2 = obj4?.GetType().GetProperty("wasPressedThisFrame").GetGetMethod();
			if (methodInfo2 != null)
			{
				_scanInputName = "right mouse button";
				return (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), obj4, methodInfo2);
			}
		}
		catch (Exception)
		{
		}
		return null;
	}

	private List<RowAccess> Rows()
	{
		if (_rowAccess != null)
		{
			return _rowAccess;
		}
		List<RowAccess> list = new List<RowAccess>();
		Assembly[] array = new Assembly[2] { _asmCruiser, _asmShip };
		foreach (Assembly assembly in array)
		{
			Type type = ((!(assembly == null)) ? assembly.GetType("UltimateScan.Util") : null);
			if (!(type == null))
			{
				try
				{
					list.Add(new RowAccess
					{
						Count = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), type.GetMethod("RowCount")),
						SetEnv = (Action<int, float, float, float>)Delegate.CreateDelegate(typeof(Action<int, float, float, float>), type.GetMethod("SetEnv"))
					});
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Animated color modes unavailable for one mod: " + ex.Message));
				}
			}
		}
		_rowAccess = list;
		return list;
	}

	private void CustomColors()
	{
		if (!IsCustom(_mode))
		{
			return;
		}
		float t = (float)(Clock.Elapsed.TotalSeconds * (double)_speed.Value);
		List<RowAccess> list = Rows();
		for (int i = 0; i < list.Count; i++)
		{
			int num = list[i].Count();
			for (int j = 0; j < num; j++)
			{
				Palette(_mode, t, j, out var r, out var g, out var b);
				list[i].SetEnv(j, r, g, b);
			}
		}
		int num2 = UltimateStyle.RowCount();
		for (int k = 0; k < num2; k++)
		{
			Palette(_mode, t, k, out var r2, out var g2, out var b2);
			UltimateStyle.SetEnv(k, r2, g2, b2);
		}
	}

	public static void Palette(int mode, float t, int idx, out float r, out float g, out float b)
	{
		Palette((Mode)mode, t, idx, out r, out g, out b);
	}

	private static void Palette(Mode m, float t, int idx, out float r, out float g, out float b)
	{
		switch (m)
		{
		case Mode.Fire:
			Gradient(FireStops, t * 0.6f + (float)idx * 0.13f + 0.06f * (float)Math.Sin(t * 17f + (float)idx * 2f), out r, out g, out b);
			break;
		case Mode.Ocean:
			Gradient(OceanStops, t * 0.5f + (float)idx * 0.1f, out r, out g, out b);
			break;
		case Mode.Neon:
			Gradient(NeonStops, t * 0.7f + (float)idx * 0.12f, out r, out g, out b);
			break;
		case Mode.Sunset:
			Gradient(SunsetStops, t * 0.4f + (float)idx * 0.1f, out r, out g, out b);
			break;
		case Mode.Toxic:
			Gradient(ToxicStops, t * 0.6f + (float)idx * 0.12f, out r, out g, out b);
			break;
		case Mode.Ice:
			Gradient(IceStops, t * 0.4f + (float)idx * 0.1f, out r, out g, out b);
			break;
		case Mode.Gold:
			Gradient(GoldStops, t * 0.8f + (float)idx * 0.08f, out r, out g, out b);
			break;
		case Mode.Disco:
		{
			int num = (int)Math.Floor(t * 3f) + idx * 7;
			uint num2 = (uint)(num * -1640531535);
			num2 ^= num2 >> 15;
			Hsv((float)(num2 % 1000) / 1000f, out r, out g, out b);
			break;
		}
		default:
			r = (g = (b = 1f));
			break;
		}
	}

	private static void Gradient(float[][] stops, float u, out float r, out float g, out float b)
	{
		u -= (float)Math.Floor(u);
		float num = u * (float)stops.Length;
		int num2 = (int)num;
		float num3 = num - (float)num2;
		num3 = num3 * num3 * (3f - 2f * num3);
		float[] array = stops[num2 % stops.Length];
		float[] array2 = stops[(num2 + 1) % stops.Length];
		r = array[0] + (array2[0] - array[0]) * num3;
		g = array[1] + (array2[1] - array[1]) * num3;
		b = array[2] + (array2[2] - array[2]) * num3;
	}

	private static void Hsv(float h, out float r, out float g, out float b)
	{
		float num = h * 6f;
		int num2 = (int)num;
		float num3 = num - (float)num2;
		float num4 = 1f - num3;
		switch (num2 % 6)
		{
		case 0:
			r = 1f;
			g = num3;
			b = 0f;
			break;
		case 1:
			r = num4;
			g = 1f;
			b = 0f;
			break;
		case 2:
			r = 0f;
			g = 1f;
			b = num3;
			break;
		case 3:
			r = 0f;
			g = num4;
			b = 1f;
			break;
		case 4:
			r = num3;
			g = 0f;
			b = 1f;
			break;
		default:
			r = 1f;
			g = 0f;
			b = num4;
			break;
		}
	}

	public static void ParseOffset(string text, out float x, out float y)
	{
		x = (y = 0f);
		if (!string.IsNullOrEmpty(text))
		{
			string[] array = text.Replace("(", string.Empty).Replace(")", string.Empty).Replace(";", ",")
				.Split(',');
			float result = 0f;
			float result2 = 0f;
			if (array.Length >= 1)
			{
				float.TryParse(array[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out result);
			}
			if (array.Length >= 2)
			{
				float.TryParse(array[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out result2);
			}
			x = result;
			y = result2;
		}
	}

	private static object StaticField(Assembly asm, string type, string field)
	{
		Type type2 = ((!(asm == null)) ? asm.GetType(type) : null);
		FieldInfo fieldInfo = ((!(type2 == null)) ? type2.GetField(field, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) : null);
		return (!(fieldInfo == null)) ? fieldInfo.GetValue(null) : null;
	}

	private void FindModEntries()
	{
		try
		{
			_cruiserDisplayTime = StaticField(_asmCruiser, "CruiserScrapCounter.Plugin", "DisplayTime");
			_cruiserOffX = StaticField(_asmCruiser, "CruiserScrapCounter.Plugin", "OffsetX");
			_cruiserOffY = StaticField(_asmCruiser, "CruiserScrapCounter.Plugin", "OffsetY");
			object obj = StaticField(_asmShip, "ShipLootCruiser.ShipLootCruiser", "config");
			FieldInfo fieldInfo = obj?.GetType().GetField("DisplayTime", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			_shipDisplayTime = ((!(fieldInfo == null)) ? fieldInfo.GetValue(obj) : null);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not find the mods' own settings: " + ex.Message));
		}
	}

	private void PushShared()
	{
		ParseOffset(_cruiserOffset.Value, out var x, out var y);
		SetEntry(_cruiserDisplayTime, _displayTime.Value);
		SetEntry(_shipDisplayTime, _displayTime.Value);
		SetEntry(_cruiserOffX, x);
		SetEntry(_cruiserOffY, y);
	}

	private void SetEntry(object entry, float value)
	{
		if (entry == null)
		{
			return;
		}
		try
		{
			entry.GetType().GetProperty("BoxedValue").SetValue(entry, value, null);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not apply a shared setting: " + ex.Message));
		}
	}

	private void ConfigureCruiser(Assembly asm)
	{
		try
		{
			Type type = asm.GetType("CruiserScrapCounter.CruiserScanPatch");
			SetRow(type, "Cruiser", _cruiserText, _cruiserLine);
			SetRow(type, "Count", _countText, _countLine);
			Set(asm.GetType("CruiserScrapCounter.LootTracker"), "ExcludeBodies", !_scanBodies.Value);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Could not configure CruiserScrapCounter: " + ex));
		}
	}

	private void ConfigureQuota()
	{
		Split2(_labels.Value, "OVERTIME", out var a, out var b);
		QuotaTracker.QuotaLabel = a;
		QuotaTracker.OvertimeLabel = b;
		ParseOffset(_quotaOffset.Value, out var x, out var y);
		QuotaTracker.OffsetX = x;
		QuotaTracker.OffsetY = y;
		QuotaTracker.AutoDisplay = _autoDisplay.Value;
		QuotaTracker.HideWhenDead = !_deadDisplay.Value;
		QuotaTracker.QuotaTextHas = _quotaText.Has;
		QuotaTracker.QuotaTextR = _quotaText.R;
		QuotaTracker.QuotaTextG = _quotaText.G;
		QuotaTracker.QuotaTextB = _quotaText.B;
		QuotaTracker.QuotaLineHas = _quotaLine.Has;
		QuotaTracker.QuotaLineR = _quotaLine.R;
		QuotaTracker.QuotaLineG = _quotaLine.G;
		QuotaTracker.QuotaLineB = _quotaLine.B;
		QuotaTracker.OvertimeTextHas = _overtimeText.Has;
		QuotaTracker.OvertimeTextR = _overtimeText.R;
		QuotaTracker.OvertimeTextG = _overtimeText.G;
		QuotaTracker.OvertimeTextB = _overtimeText.B;
		QuotaTracker.OvertimeLineHas = _overtimeLine.Has;
		QuotaTracker.OvertimeLineR = _overtimeLine.R;
		QuotaTracker.OvertimeLineG = _overtimeLine.G;
		QuotaTracker.OvertimeLineB = _overtimeLine.B;
	}

	private void ConfigureAuto()
	{
		if (AutoScan.FinalScanSetting != _finalScan.Value)
		{
			AutoScan.SessionFinal = null;
		}
		AutoScan.FinalScanSetting = _finalScan.Value;
		AutoScan.FinalFormat = _finalFormat.Value;
		if (AutoScan.AutoCruiserScan != _cruiserChat.Value)
		{
			AutoScan.SessionCruiser = null;
		}
		if (AutoScan.ChatAutoScan != _chatScan.Value)
		{
			AutoScan.SessionScan = null;
		}
		AutoScan.ChatAutoScan = _chatScan.Value;
		AutoScan.AutoCruiserScan = _cruiserChat.Value;
		AutoScan.DayStart = _dayStart.Value;
		AutoScan.IntervalScan = _interval.Value;
		AutoScan.CruiserIntervalScan = _cruiserInterval.Value;
		AutoScan.ScanFormat = _scanFormat.Value;
		AutoScan.CruiserFormat = _cruiserScanFormat.Value;
		AutoScan.DayStartDelay = _dayDelay.Value;
		AutoScan.ScanBodies = _scanBodies.Value;
		AutoScan.AnnounceColor = _announceColor.Value;
	}

	private void InstallQuotaTracker()
	{
		QuotaTracker.Info = delegate(string m)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)m);
		};
		QuotaTracker.Warn = delegate(string m)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)m);
		};
		QuotaTracker.ItemsChanged = MarkDirty;
		_quotaInstallPending = true;
	}

	private void ConfigureShip(Assembly asm)
	{
		try
		{
			Type type = asm.GetType("ShipLootCruiser.Patches.HudManagerPatcher");
			SetRow(type, "Ship", _shipText, _shipLine);
			ParseOffset(_shipOffset.Value, out var x, out var y);
			Set(type, "OffsetX", x);
			Set(type, "OffsetY", y);
			Set(type, "Template", _shipFormat.Value.Replace("\\n", "\n"));
			Set(type, "ShowAnywhere", _shipAnywhere.Value);
			Set(type, "ExcludeBodies", !_scanBodies.Value);
			Set(type, "CacheSeconds", _shipCache.Value);
			Set(type, "LogTiming", _logTiming.Value);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Could not configure ShipLootCruiser: " + ex));
		}
	}

	private static void SetRow(Type t, string prefix, ColorCfg text, ColorCfg line)
	{
		Set(t, prefix + "TextHas", text.Has);
		Set(t, prefix + "TextR", text.R);
		Set(t, prefix + "TextG", text.G);
		Set(t, prefix + "TextB", text.B);
		Set(t, prefix + "LineHas", line.Has);
		Set(t, prefix + "LineR", line.R);
		Set(t, prefix + "LineG", line.G);
		Set(t, prefix + "LineB", line.B);
	}

	private static void Set(Type t, string field, object value)
	{
		FieldInfo field2 = t.GetField(field, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
		if (field2 == null)
		{
			throw new MissingFieldException(t.FullName, field);
		}
		field2.SetValue