Decompiled source of DashboardAlarms v1.0.1

DashboardAlarms.dll

Decompiled 10 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using crecheng.DSPModSave;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("DashboardAlarms.LogicTests")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("DashboardAlarms")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1+67e33bd4bb9f50211a1f53cb3ed6a7a6f0afe377")]
[assembly: AssemblyProduct("DashboardAlarms")]
[assembly: AssemblyTitle("DashboardAlarms")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DashboardAlarms
{
	public static class AlarmManager
	{
		public const int TicksPerSecond = 60;

		public static readonly List<AlarmDefinition> Alarms = new List<AlarmDefinition>();

		public static float SampleSeconds = 2f;

		public static float StockRefreshSeconds = 30f;

		private static long lastSampleTick = -1L;

		private static long lastStockRequestTick = -1L;

		private static bool stockRequested;

		private static bool stockFresh;

		private static ProductionExtraInfoCalculator hookedCalculator;

		public static float AlarmVolume = 0.5f;

		private static AudioSource alarmSource;

		public static int RaisedCount
		{
			get
			{
				int num = 0;
				foreach (AlarmDefinition alarm in Alarms)
				{
					if (alarm.IsRaised)
					{
						num++;
					}
				}
				return num;
			}
		}

		public static int ShownCount
		{
			get
			{
				int num = 0;
				foreach (AlarmDefinition alarm in Alarms)
				{
					if (alarm.IsShown)
					{
						num++;
					}
				}
				return num;
			}
		}

		public static AlarmDefinition Find(int statPlanId)
		{
			foreach (AlarmDefinition alarm in Alarms)
			{
				if (alarm.statPlanId == statPlanId)
				{
					return alarm;
				}
			}
			return null;
		}

		public static AlarmDefinition CreateFor(StatPlan plan)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected I4, but got Unknown
			AlarmDefinition alarmDefinition = new AlarmDefinition
			{
				statPlanId = plan.id,
				planType = (int)plan.type,
				itemId = StatReader.ItemId(plan),
				astroFilter = StatReader.AstroFilter(plan),
				metric = (StatReader.SupportsStock(plan) ? AlarmMetric.Stock : AlarmMetric.Production)
			};
			Alarms.Add(alarmDefinition);
			return alarmDefinition;
		}

		public static void Remove(AlarmDefinition a)
		{
			Alarms.Remove(a);
		}

		public static void Clear()
		{
			Alarms.Clear();
			lastSampleTick = -1L;
			lastStockRequestTick = -1L;
			stockRequested = false;
			stockFresh = false;
			hookedCalculator = null;
		}

		public static StatPlan ResolvePlan(GameData data, AlarmDefinition a)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Invalid comparison between Unknown and I4
			StatPlanPool val = data?.statistics?.charts?.statPlans;
			if (val == null || a.statPlanId <= 0 || a.statPlanId >= val.cursor)
			{
				return null;
			}
			StatPlan val2 = val[a.statPlanId];
			if (val2 == null || val2.id != a.statPlanId || (int)val2.type != a.planType)
			{
				return null;
			}
			a.itemId = StatReader.ItemId(val2);
			a.astroFilter = StatReader.AstroFilter(val2);
			return val2;
		}

		public static void Tick()
		{
			GameData data = GameMain.data;
			if (data == null || GameMain.isPaused || !GameMain.isRunning || Alarms.Count == 0 || data.statistics?.charts?.statPlans == null || data.statistics.production?.extraInfoCalculator == null)
			{
				return;
			}
			long gameTick = GameMain.gameTick;
			HookCalculator(data);
			RequestStockRefreshIfDue(data, gameTick);
			if (lastSampleTick >= 0 && gameTick - lastSampleTick < (long)(SampleSeconds * 60f) && gameTick >= lastSampleTick)
			{
				return;
			}
			lastSampleTick = gameTick;
			bool flag = stockFresh;
			stockFresh = false;
			for (int num = Alarms.Count - 1; num >= 0; num--)
			{
				AlarmDefinition alarmDefinition = Alarms[num];
				StatPlan val = ResolvePlan(data, alarmDefinition);
				if (val == null)
				{
					Alarms.RemoveAt(num);
				}
				else
				{
					double num2 = double.NaN;
					if (alarmDefinition.metric == AlarmMetric.Stock)
					{
						if (flag)
						{
							AstroStorageStatPlan val2 = (AstroStorageStatPlan)(object)((val is AstroStorageStatPlan) ? val : null);
							if (val2 != null && StatReader.TryReadStock(val2, out var stock))
							{
								num2 = stock;
							}
						}
					}
					else
					{
						AstroItemProductionStatPlan val3 = (AstroItemProductionStatPlan)(object)((val is AstroItemProductionStatPlan) ? val : null);
						if (val3 != null)
						{
							if (flag && Metrics.NeedsMax(alarmDefinition.metric))
							{
								alarmDefinition.lastMax = StatReader.ReadMaxProduction(val3);
								alarmDefinition.hasMax = true;
							}
							if (StatReader.TryReadRates(data, val3, out var production, out var consumption))
							{
								num2 = ComputeSample(alarmDefinition.metric, production, consumption, alarmDefinition.hasMax ? alarmDefinition.lastMax : double.NaN);
							}
						}
					}
					if (!alarmDefinition.enabled || alarmDefinition.isDraft)
					{
						if (!double.IsNaN(num2))
						{
							alarmDefinition.lastValue = num2;
							alarmDefinition.hasValue = true;
						}
						alarmDefinition.state = AlarmState.Normal;
						alarmDefinition.conditionSinceTick = -1L;
					}
					else
					{
						Evaluate(alarmDefinition, gameTick, num2);
					}
				}
			}
		}

		internal static double ComputeSample(AlarmMetric metric, double production, double consumption, double max)
		{
			switch (metric)
			{
			case AlarmMetric.Production:
				return production;
			case AlarmMetric.Consumption:
				return consumption;
			case AlarmMetric.Net:
				return production - consumption;
			case AlarmMetric.MaxProduction:
				return max;
			case AlarmMetric.UsePercent:
				if (!double.IsNaN(max) && !(max <= 0.0))
				{
					return consumption / max * 100.0;
				}
				return double.NaN;
			default:
				return double.NaN;
			}
		}

		internal static void Evaluate(AlarmDefinition a, long now, double sample)
		{
			if (!double.IsNaN(sample))
			{
				long num = (long)(Math.Max(0.5f, a.averageMinutes) * 60f * 60f);
				a.lastAverage = a.history.Mean;
				if (a.history.Count <= 0 || a.history.Span(now) < num / 2)
				{
					a.lastAverage = double.NaN;
				}
				a.lastValue = sample;
				a.hasValue = true;
				if (a.trigger != AlarmTrigger.DropPercent || !ConditionMet(a))
				{
					a.history.Add(now, sample, num);
				}
			}
			if (!a.hasValue)
			{
				return;
			}
			bool flag = ConditionMet(a);
			long num2 = (long)(Math.Max(0f, a.holdSeconds) * 60f);
			if (a.state == AlarmState.Snoozed)
			{
				if (!flag)
				{
					a.state = AlarmState.Normal;
					a.conditionSinceTick = -1L;
					return;
				}
				if (now < a.snoozeUntilTick)
				{
					return;
				}
				a.state = AlarmState.Alarming;
				a.lastSoundTick = -1L;
				a.conditionSinceTick = now - num2;
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)("Snooze ended, still alarming: " + Describe(a) + " (value " + Format(a.lastValue) + ")"));
				}
			}
			if (!flag)
			{
				a.state = AlarmState.Normal;
				a.conditionSinceTick = -1L;
				return;
			}
			if (a.conditionSinceTick < 0 || a.conditionSinceTick > now)
			{
				a.conditionSinceTick = now;
			}
			switch (a.state)
			{
			case AlarmState.Normal:
			case AlarmState.Pending:
				if (now - a.conditionSinceTick >= num2)
				{
					a.state = AlarmState.Alarming;
					a.lastSoundTick = -1L;
					ManualLogSource log2 = Plugin.Log;
					if (log2 != null)
					{
						log2.LogInfo((object)("Alarm raised: " + Describe(a) + " (value " + Format(a.lastValue) + ")"));
					}
				}
				else
				{
					a.state = AlarmState.Pending;
				}
				break;
			}
			if (a.state == AlarmState.Alarming && a.playSound)
			{
				long num3 = (long)(a.repeatSoundSeconds * 60f);
				if (a.lastSoundTick < 0 || (num3 > 0 && now - a.lastSoundTick >= num3) || a.lastSoundTick > now)
				{
					PlaySounds(a.sounds);
					a.lastSoundTick = now;
				}
			}
		}

		public static bool ConditionMet(AlarmDefinition a)
		{
			double lastValue = a.lastValue;
			if (double.IsNaN(lastValue))
			{
				return false;
			}
			switch (a.trigger)
			{
			case AlarmTrigger.Below:
				return lastValue < a.threshold;
			case AlarmTrigger.Above:
				return lastValue > a.threshold;
			case AlarmTrigger.DropPercent:
			{
				double lastAverage = a.lastAverage;
				if (double.IsNaN(lastAverage) || lastAverage <= 0.0)
				{
					return false;
				}
				return lastValue < lastAverage * (1.0 - a.dropPercent / 100.0);
			}
			default:
				return false;
			}
		}

		public static void Snooze(AlarmDefinition a, float minutes)
		{
			Snooze(a, minutes, GameMain.gameTick);
		}

		internal static void Snooze(AlarmDefinition a, float minutes, long now)
		{
			if (a.state == AlarmState.Alarming || a.state == AlarmState.Snoozed)
			{
				a.state = AlarmState.Snoozed;
				a.snoozeUntilTick = now + (long)(Math.Max(0.1f, minutes) * 60f * 60f);
			}
		}

		public static void Unsnooze(AlarmDefinition a)
		{
			Unsnooze(a, GameMain.gameTick);
		}

		internal static void Unsnooze(AlarmDefinition a, long now)
		{
			if (a.state == AlarmState.Snoozed)
			{
				a.snoozeUntilTick = now;
			}
		}

		public static float SnoozeSecondsLeft(AlarmDefinition a)
		{
			if (a.state != AlarmState.Snoozed)
			{
				return 0f;
			}
			return (float)Math.Max(0L, a.snoozeUntilTick - GameMain.gameTick) / 60f;
		}

		public static void SnoozeAllRaised()
		{
			foreach (AlarmDefinition alarm in Alarms)
			{
				if (alarm.IsRaised)
				{
					Snooze(alarm, alarm.snoozeMinutes);
				}
			}
		}

		public static void PlaySounds(List<string> names, bool diagnose = false)
		{
			if (names == null)
			{
				return;
			}
			if (diagnose)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)(string.Format("Sound test: {0} sound(s) [{1}]; ", names.Count, string.Join(", ", names.ToArray())) + $"alarm volume {AlarmVolume:0.##}, play with sound off {Plugin.PlayWithSoundOff}, game master {VFAudio.audioVolume:0.##}, game effects {VFAudio.soundVolume:0.##}, final x{GameVolumeFactor(Plugin.PlayWithSoundOff):0.##}; " + $"listener volume {AudioListener.volume:0.##}, background mute {VFAudio.backgroundMute}, focused {Application.isFocused}"));
				}
			}
			foreach (string name in names)
			{
				PlaySound(name, diagnose);
			}
		}

		public static void PlaySound(string name, bool diagnose = false)
		{
			PlaySound(name, AlarmVolume, Plugin.PlayWithSoundOff, diagnose);
		}

		public static void PlaySound(string name, float alarmVolume, bool playWithSoundOff, bool diagnose = false)
		{
			if (string.IsNullOrEmpty(name))
			{
				name = "warning-popup-1";
			}
			try
			{
				AudioProto val = LDB.audios[name];
				if (val == null)
				{
					ManualLogSource log = Plugin.Log;
					if (log != null)
					{
						log.LogWarning((object)("Sound '" + name + "' is not one of the game's sounds"));
					}
					return;
				}
				if ((Object)(object)val.audioClip == (Object)null)
				{
					val.Preload();
				}
				AudioClip audioClip = val.audioClip;
				if ((Object)(object)audioClip == (Object)null)
				{
					ManualLogSource log2 = Plugin.Log;
					if (log2 != null)
					{
						log2.LogWarning((object)("Sound '" + name + "': the game has no clip for it"));
					}
					return;
				}
				AudioSource val2 = EnsureSource();
				float num = Mathf.Clamp01(alarmVolume) * GameVolumeFactor(playWithSoundOff) * ((val.Volume > 0f) ? val.Volume : 1f);
				val2.PlayOneShot(audioClip, num);
				if (diagnose)
				{
					ManualLogSource log3 = Plugin.Log;
					if (log3 != null)
					{
						log3.LogInfo((object)$"Sound '{name}': clip {((Object)audioClip).name} ({audioClip.length:0.##}s), volume {num:0.###}, playing {val2.isPlaying}");
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log4 = Plugin.Log;
				if (log4 != null)
				{
					log4.LogWarning((object)("Could not play sound '" + name + "': " + ex.GetType().Name + ": " + ex.Message));
				}
			}
		}

		internal static float GameVolumeFactor(bool playWithSoundOff)
		{
			if (!playWithSoundOff)
			{
				return Mathf.Clamp01(VFAudio.audioVolume) * Mathf.Clamp01(VFAudio.soundVolume);
			}
			return 1f;
		}

		private static AudioSource EnsureSource()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			if ((Object)(object)alarmSource != (Object)null)
			{
				return alarmSource;
			}
			GameObject val = new GameObject("DashboardAlarms.Audio");
			Object.DontDestroyOnLoad((Object)val);
			alarmSource = val.AddComponent<AudioSource>();
			alarmSource.playOnAwake = false;
			alarmSource.spatialBlend = 0f;
			alarmSource.bypassEffects = true;
			alarmSource.bypassListenerEffects = true;
			alarmSource.bypassReverbZones = true;
			alarmSource.priority = 0;
			return alarmSource;
		}

		private static void HookCalculator(GameData data)
		{
			ProductionExtraInfoCalculator val = data.statistics?.production?.extraInfoCalculator;
			if (val != null && val != hookedCalculator)
			{
				val.onEndCalculate = (Action<double>)Delegate.Combine(val.onEndCalculate, new Action<double>(OnCalculatorFinished));
				hookedCalculator = val;
			}
		}

		private static void OnCalculatorFinished(double _)
		{
			if (stockRequested)
			{
				stockFresh = true;
			}
			stockRequested = false;
		}

		public static void RequestRecountSoon()
		{
			lastStockRequestTick = -1L;
		}

		private static void RequestStockRefreshIfDue(GameData data, long now)
		{
			long num = (long)(Math.Max(5f, StockRefreshSeconds) * 60f);
			if (lastStockRequestTick >= 0 && now - lastStockRequestTick < num && now >= lastStockRequestTick && (!stockRequested || now - lastStockRequestTick <= num * 4))
			{
				return;
			}
			bool flag = false;
			foreach (AlarmDefinition alarm in Alarms)
			{
				if (!alarm.enabled || !Metrics.NeedsRecount(alarm.metric))
				{
					continue;
				}
				StatPlan val = ResolvePlan(data, alarm);
				AstroStorageStatPlan val2 = (AstroStorageStatPlan)(object)((val is AstroStorageStatPlan) ? val : null);
				if (val2 != null && val2.itemId > 0)
				{
					val2.CalculateExtraInfo();
					flag = true;
					continue;
				}
				AstroItemProductionStatPlan val3 = (AstroItemProductionStatPlan)(object)((val is AstroItemProductionStatPlan) ? val : null);
				if (val3 != null && val3.itemId > 0)
				{
					val3.CalculateExtraInfo();
					flag = true;
				}
			}
			if (flag)
			{
				stockRequested = true;
				lastStockRequestTick = now;
			}
		}

		public static string Describe(AlarmDefinition a)
		{
			GameData data = GameMain.data;
			string text = StatReader.ItemName(a.itemId);
			string text2 = ((data != null) ? StatReader.AreaName(data, a.astroFilter) : "");
			string text3 = Metrics.Name(a.metric);
			string text4 = Metrics.Unit(a.metric);
			string text5 = ((a.trigger == AlarmTrigger.Below) ? ("< " + Format(a.threshold) + text4) : ((a.trigger == AlarmTrigger.Above) ? ("> " + Format(a.threshold) + text4) : $"{a.dropPercent:0.#}% below {a.averageMinutes:0.#}-min average"));
			return text + " " + text3 + " (" + text2 + ") " + text5;
		}

		public static string FormatValue(AlarmDefinition a, double v)
		{
			if (!double.IsNaN(v))
			{
				return Format(v) + Metrics.Unit(a.metric);
			}
			return "-";
		}

		public static string Format(double v)
		{
			if (double.IsNaN(v))
			{
				return "-";
			}
			double num = Math.Abs(v);
			if (num >= 1000000000.0)
			{
				return (v / 1000000000.0).ToString("0.##") + "G";
			}
			if (num >= 1000000.0)
			{
				return (v / 1000000.0).ToString("0.##") + "M";
			}
			if (num >= 10000.0)
			{
				return (v / 1000.0).ToString("0.#") + "k";
			}
			return v.ToString("0.#");
		}

		public static void Export(BinaryWriter w)
		{
			w.Write(1);
			int num = 0;
			foreach (AlarmDefinition alarm in Alarms)
			{
				if (!alarm.isDraft)
				{
					num++;
				}
			}
			w.Write(num);
			foreach (AlarmDefinition alarm2 in Alarms)
			{
				if (!alarm2.isDraft)
				{
					alarm2.Write(w);
				}
			}
		}

		public static void Import(BinaryReader r)
		{
			Clear();
			r.ReadInt32();
			int num = r.ReadInt32();
			for (int i = 0; i < num; i++)
			{
				AlarmDefinition alarmDefinition = AlarmDefinition.Read(r);
				alarmDefinition.ResetRuntime();
				Alarms.Add(alarmDefinition);
			}
			ManualLogSource log = Plugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"Loaded {Alarms.Count} dashboard alarm(s)");
			}
		}
	}
	public enum AlarmMetric
	{
		Production,
		Consumption,
		Net,
		Stock,
		MaxProduction,
		UsePercent
	}
	public enum AlarmTrigger
	{
		Below,
		Above,
		DropPercent
	}
	public enum AlarmState
	{
		Normal = 0,
		Pending = 1,
		Alarming = 2,
		Snoozed = 4
	}
	public static class Metrics
	{
		public static bool NeedsRecount(AlarmMetric m)
		{
			if (m != AlarmMetric.Stock)
			{
				return NeedsMax(m);
			}
			return true;
		}

		public static bool NeedsMax(AlarmMetric m)
		{
			if (m != AlarmMetric.MaxProduction)
			{
				return m == AlarmMetric.UsePercent;
			}
			return true;
		}

		public static string Unit(AlarmMetric m)
		{
			return m switch
			{
				AlarmMetric.UsePercent => "%", 
				AlarmMetric.Stock => "", 
				_ => "/min", 
			};
		}

		public static string Name(AlarmMetric m)
		{
			return m switch
			{
				AlarmMetric.Production => "production", 
				AlarmMetric.Consumption => "consumption", 
				AlarmMetric.Net => "net", 
				AlarmMetric.Stock => "stock", 
				AlarmMetric.MaxProduction => "max production", 
				AlarmMetric.UsePercent => "use % of max production", 
				_ => m.ToString(), 
			};
		}
	}
	public class AlarmDefinition
	{
		public int statPlanId;

		public int planType;

		public int itemId;

		public int astroFilter;

		public bool enabled = true;

		public AlarmMetric metric;

		public AlarmTrigger trigger;

		public double threshold;

		public double dropPercent = 20.0;

		public float averageMinutes = 10f;

		public float holdSeconds = 30f;

		public bool playSound = true;

		public List<string> sounds = new List<string> { "warning-popup-1" };

		public float repeatSoundSeconds = 30f;

		public float snoozeMinutes = 10f;

		public AlarmState state;

		public long conditionSinceTick = -1L;

		public long snoozeUntilTick;

		public long lastSoundTick = -1L;

		public double lastValue = double.NaN;

		public double lastAverage = double.NaN;

		public bool hasValue;

		public double lastMax = double.NaN;

		public bool hasMax;

		public bool isDraft;

		public readonly RollingAverage history = new RollingAverage();

		public const int SaveVersion = 2;

		public bool IsRaised => state == AlarmState.Alarming;

		public bool IsShown
		{
			get
			{
				if (state != AlarmState.Alarming)
				{
					return state == AlarmState.Snoozed;
				}
				return true;
			}
		}

		public void Write(BinaryWriter w)
		{
			w.Write(2);
			w.Write(statPlanId);
			w.Write(planType);
			w.Write(itemId);
			w.Write(astroFilter);
			w.Write(enabled);
			w.Write((int)metric);
			w.Write((int)trigger);
			w.Write(threshold);
			w.Write(dropPercent);
			w.Write(averageMinutes);
			w.Write(holdSeconds);
			w.Write(playSound);
			w.Write(sounds.Count);
			foreach (string sound in sounds)
			{
				w.Write(sound ?? "warning-popup-1");
			}
			w.Write(repeatSoundSeconds);
			w.Write(snoozeMinutes);
		}

		public static AlarmDefinition Read(BinaryReader r)
		{
			int num = r.ReadInt32();
			AlarmDefinition alarmDefinition = new AlarmDefinition
			{
				statPlanId = r.ReadInt32(),
				planType = r.ReadInt32(),
				itemId = r.ReadInt32(),
				astroFilter = r.ReadInt32(),
				enabled = r.ReadBoolean(),
				metric = (AlarmMetric)r.ReadInt32(),
				trigger = (AlarmTrigger)r.ReadInt32(),
				threshold = r.ReadDouble(),
				dropPercent = r.ReadDouble(),
				averageMinutes = r.ReadSingle(),
				holdSeconds = r.ReadSingle(),
				playSound = r.ReadBoolean()
			};
			alarmDefinition.sounds.Clear();
			if (num >= 2)
			{
				int num2 = r.ReadInt32();
				for (int i = 0; i < num2; i++)
				{
					alarmDefinition.sounds.Add(r.ReadString());
				}
			}
			else
			{
				alarmDefinition.sounds.Add(r.ReadString());
			}
			alarmDefinition.repeatSoundSeconds = r.ReadSingle();
			alarmDefinition.snoozeMinutes = r.ReadSingle();
			return alarmDefinition;
		}

		public void ResetRuntimeTimersOnly()
		{
			state = AlarmState.Normal;
			conditionSinceTick = -1L;
			snoozeUntilTick = 0L;
			lastSoundTick = -1L;
		}

		public void ResetRuntime()
		{
			state = AlarmState.Normal;
			conditionSinceTick = -1L;
			snoozeUntilTick = 0L;
			lastSoundTick = -1L;
			lastValue = double.NaN;
			lastAverage = double.NaN;
			hasValue = false;
			history.Clear();
		}
	}
	public class RollingAverage
	{
		private readonly Queue<KeyValuePair<long, double>> samples = new Queue<KeyValuePair<long, double>>();

		private double sum;

		public int Count => samples.Count;

		public double Mean
		{
			get
			{
				if (samples.Count != 0)
				{
					return sum / (double)samples.Count;
				}
				return double.NaN;
			}
		}

		public void Clear()
		{
			samples.Clear();
			sum = 0.0;
		}

		public void Add(long tick, double value, long windowTicks)
		{
			samples.Enqueue(new KeyValuePair<long, double>(tick, value));
			sum += value;
			while (samples.Count > 0 && samples.Peek().Key < tick - windowTicks)
			{
				sum -= samples.Dequeue().Value;
			}
		}

		public long Span(long nowTick)
		{
			if (samples.Count != 0)
			{
				return nowTick - samples.Peek().Key;
			}
			return 0L;
		}
	}
	public static class Sounds
	{
		public const string Default = "warning-popup-1";

		public static readonly string[,] Options = new string[5, 2]
		{
			{ "warning-popup-1", "Warning popup" },
			{ "warning-popup-0", "Tutorial warning" },
			{ "df-alarm", "Dark Fog alarm" },
			{ "ui-error", "UI error" },
			{ "research-complete", "Research complete" }
		};
	}
	public static class AlarmWindow
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static WindowFunction <0>__DrawEditor;

			public static WindowFunction <1>__DrawList;
		}

		private const int EditorWindowId = 228958624;

		private const int ListWindowId = 228958625;

		private static AlarmDefinition editing;

		private static bool editingIsNew;

		private static Rect editorRect = new Rect(0f, 0f, 440f, 470f);

		private static string thresholdText = "";

		private static string dropText = "";

		private static string averageText = "";

		private static string holdText = "";

		private static string repeatText = "";

		private static string snoozeText = "";

		private static bool listOpen;

		private static Rect listRect = new Rect(0f, 0f, 620f, 360f);

		private static Vector2 listScroll;

		private static Rect bannerRect;

		private static GUIStyle bannerStyle;

		private static GUIStyle wrapLabel;

		private static GUIStyle bannerLineStyle;

		private static GUIStyle bannerSnoozedStyle;

		private static GUIStyle bannerTitleStyle;

		private static readonly List<Rect> activeRects = new List<Rect>();

		private static float bannerContentH;

		private static readonly Dictionary<GUIStyle, GUIStyle> singleLine = new Dictionary<GUIStyle, GUIStyle>();

		private const string RemoveAsk = "Remove...";

		private const string RemoveYes = "Delete alarm";

		private const string RemoveNo = "Keep";

		private static AlarmDefinition confirmRemove;

		private const string EditLabel = "Edit";

		private const string SnoozeAllLabel = "Snooze all";

		private static readonly AlarmMetric[] RateMetrics = new AlarmMetric[5]
		{
			AlarmMetric.Production,
			AlarmMetric.Consumption,
			AlarmMetric.Net,
			AlarmMetric.MaxProduction,
			AlarmMetric.UsePercent
		};

		private static readonly string[] RateMetricLabels = new string[5] { "Production/min", "Consumption/min", "Net/min", "Max production/min", "Use % of max" };

		public static bool EditorOpen => editing != null;

		public static bool MouseOverUs
		{
			get
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				Vector2 val = default(Vector2);
				((Vector2)(ref val))..ctor(Input.mousePosition.x, (float)Screen.height - Input.mousePosition.y);
				float scale = Scale;
				val /= scale;
				if ((editing == null || !((Rect)(ref editorRect)).Contains(val)) && (!listOpen || !((Rect)(ref listRect)).Contains(val)))
				{
					if (AlarmManager.ShownCount > 0)
					{
						return ((Rect)(ref bannerRect)).Contains(val);
					}
					return false;
				}
				return true;
			}
		}

		public static bool Typing
		{
			get
			{
				if (editing != null || listOpen)
				{
					return GUIUtility.keyboardControl != 0;
				}
				return false;
			}
		}

		private static float Scale => Mathf.Max(0.5f, Plugin.UiScale);

		public static List<Rect> ActiveRects()
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			activeRects.Clear();
			if (GameMain.data == null || !GameMain.isRunning || !((Object)(object)UIRoot.instance != (Object)null) || !((ManualBehaviour)UIRoot.instance.uiGame).active)
			{
				return activeRects;
			}
			if (editing != null)
			{
				activeRects.Add(editorRect);
			}
			if (listOpen)
			{
				activeRects.Add(listRect);
			}
			if (AlarmManager.ShownCount > 0 && ((Rect)(ref bannerRect)).width > 0f)
			{
				activeRects.Add(bannerRect);
			}
			return activeRects;
		}

		public static void OpenEditor(StatPlan plan)
		{
			AlarmDefinition alarmDefinition = AlarmManager.Find(plan.id);
			if (alarmDefinition != null)
			{
				editing = alarmDefinition;
				editingIsNew = false;
			}
			else
			{
				editing = AlarmManager.CreateFor(plan);
				editing.isDraft = true;
				editingIsNew = true;
				if (StatReader.SupportsRate(plan))
				{
					editing.metric = AlarmMetric.Production;
				}
			}
			thresholdText = editing.threshold.ToString("0.###", CultureInfo.InvariantCulture);
			dropText = editing.dropPercent.ToString("0.###", CultureInfo.InvariantCulture);
			averageText = editing.averageMinutes.ToString("0.###", CultureInfo.InvariantCulture);
			holdText = editing.holdSeconds.ToString("0.###", CultureInfo.InvariantCulture);
			repeatText = editing.repeatSoundSeconds.ToString("0.###", CultureInfo.InvariantCulture);
			snoozeText = editing.snoozeMinutes.ToString("0.###", CultureInfo.InvariantCulture);
			if (((Rect)(ref editorRect)).x <= 0f && ((Rect)(ref editorRect)).y <= 0f)
			{
				((Rect)(ref editorRect)).x = ((float)Screen.width / Scale - ((Rect)(ref editorRect)).width) / 2f;
				((Rect)(ref editorRect)).y = ((float)Screen.height / Scale - ((Rect)(ref editorRect)).height) / 3f;
			}
			GUIUtility.keyboardControl = 0;
		}

		public static void CloseEditor(bool discardNew)
		{
			if (editing != null && editingIsNew && discardNew)
			{
				AlarmManager.Remove(editing);
			}
			editing = null;
			editingIsNew = false;
			GUIUtility.keyboardControl = 0;
		}

		public static void ToggleList()
		{
			listOpen = !listOpen;
			if (listOpen && ((Rect)(ref listRect)).x <= 0f && ((Rect)(ref listRect)).y <= 0f)
			{
				((Rect)(ref listRect)).x = ((float)Screen.width / Scale - ((Rect)(ref listRect)).width) / 2f;
				((Rect)(ref listRect)).y = ((float)Screen.height / Scale - ((Rect)(ref listRect)).height) / 3f;
			}
		}

		public static void Reset()
		{
			editing = null;
			editingIsNew = false;
			listOpen = false;
		}

		public static void Draw()
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			if (GameMain.data == null || !GameMain.isRunning || (Object)(object)UIRoot.instance == (Object)null || !((ManualBehaviour)UIRoot.instance.uiGame).active)
			{
				return;
			}
			GUISkin skin = GUI.skin;
			GUI.skin = GameSkin.Skin;
			EnsureStyles();
			Matrix4x4 matrix = GUI.matrix;
			float scale = Scale;
			GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(scale, scale, 1f));
			try
			{
				DrawAll();
			}
			finally
			{
				GUI.matrix = matrix;
				GUI.skin = skin;
			}
		}

		private static void DrawAll()
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			DrawBanner();
			if (editing != null)
			{
				if (!AlarmManager.Alarms.Contains(editing))
				{
					editing = null;
				}
				else
				{
					Rect val = editorRect;
					object obj = <>O.<0>__DrawEditor;
					if (obj == null)
					{
						WindowFunction val2 = DrawEditor;
						<>O.<0>__DrawEditor = val2;
						obj = (object)val2;
					}
					editorRect = GUILayout.Window(228958624, val, (WindowFunction)obj, "Dashboard alarm", Array.Empty<GUILayoutOption>());
				}
			}
			if (listOpen)
			{
				Rect val3 = listRect;
				object obj2 = <>O.<1>__DrawList;
				if (obj2 == null)
				{
					WindowFunction val4 = DrawList;
					<>O.<1>__DrawList = val4;
					obj2 = (object)val4;
				}
				listRect = GUILayout.Window(228958625, val3, (WindowFunction)obj2, "Dashboard alarms", Array.Empty<GUILayoutOption>());
			}
		}

		private static void EnsureStyles()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			if (bannerStyle == null)
			{
				bannerStyle = new GUIStyle(GUI.skin.box)
				{
					fontSize = 15,
					fontStyle = (FontStyle)1,
					alignment = (TextAnchor)3,
					wordWrap = true
				};
				bannerStyle.normal.textColor = Color.white;
				wrapLabel = new GUIStyle(GUI.skin.label)
				{
					wordWrap = true
				};
				bannerLineStyle = new GUIStyle(GUI.skin.label)
				{
					wordWrap = true,
					fontSize = 14
				};
				bannerLineStyle.normal.textColor = Color.white;
				bannerTitleStyle = new GUIStyle(bannerLineStyle)
				{
					fontSize = 15,
					fontStyle = (FontStyle)1
				};
				bannerSnoozedStyle = new GUIStyle(bannerLineStyle)
				{
					fontStyle = (FontStyle)2
				};
				bannerSnoozedStyle.normal.textColor = new Color(1f, 1f, 1f, 0.6f);
			}
		}

		private static void DrawBanner()
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Expected O, but got Unknown
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Expected O, but got Unknown
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Expected O, but got Unknown
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Expected O, but got Unknown
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0330: Unknown result type (might be due to invalid IL or missing references)
			//IL_0349: Unknown result type (might be due to invalid IL or missing references)
			//IL_0350: Unknown result type (might be due to invalid IL or missing references)
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			//IL_035a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_038b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0402: Unknown result type (might be due to invalid IL or missing references)
			//IL_0440: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f5: Invalid comparison between Unknown and I4
			//IL_07f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_07fc: Unknown result type (might be due to invalid IL or missing references)
			int shownCount = AlarmManager.ShownCount;
			if (shownCount == 0)
			{
				bannerRect = Rect.zero;
				bannerContentH = 0f;
				return;
			}
			int raisedCount = AlarmManager.RaisedCount;
			int num = shownCount - raisedCount;
			float num2 = Mathf.Min(760f, (float)Screen.width / Scale - 40f);
			float num3 = num2 - 16f;
			GUIStyle button = GUI.skin.button;
			int num4 = Math.Min(shownCount, 5);
			List<KeyValuePair<AlarmDefinition, string>> list = new List<KeyValuePair<AlarmDefinition, string>>();
			for (int i = 0; i < 2; i++)
			{
				foreach (AlarmDefinition alarm in AlarmManager.Alarms)
				{
					if (((i == 0) ? (alarm.state == AlarmState.Alarming) : (alarm.state == AlarmState.Snoozed)) && list.Count < num4)
					{
						string text = ((alarm.state == AlarmState.Snoozed) ? ("(snoozed, " + FormatDuration(AlarmManager.SnoozeSecondsLeft(alarm)) + " left)  ") : "");
						list.Add(new KeyValuePair<AlarmDefinition, string>(alarm, text + AlarmManager.Describe(alarm) + "  -  now " + AlarmManager.FormatValue(alarm, alarm.lastValue)));
					}
				}
			}
			float num5 = 0f;
			bool flag = false;
			foreach (KeyValuePair<AlarmDefinition, string> item in list)
			{
				if (item.Key == confirmRemove)
				{
					flag = true;
					num5 += WrappedHeight(bannerLineStyle, RemoveQuestion(item.Key), num3 - (float)bannerLineStyle.margin.horizontal) + 6f + button.CalcHeight(new GUIContent("Delete alarm"), 80f) + 6f;
				}
				else
				{
					float width = num3 - RowButtonsWidth(button, item.Key) - 6f;
					num5 += Mathf.Max(button.CalcHeight(new GUIContent("x"), 80f), WrappedHeight(LineStyle(item.Key), item.Value, width)) + 6f;
				}
			}
			if (!flag)
			{
				confirmRemove = null;
			}
			float num6 = button.CalcHeight(new GUIContent("List"), 60f) + 6f;
			float num7 = ((shownCount > num4) ? bannerLineStyle.CalcHeight(new GUIContent("x"), num3) : 0f);
			float num8 = num6 + num5 + num7;
			float num9 = 8f + ((bannerContentH > 0f) ? bannerContentH : num8) + 8f;
			bannerRect = new Rect(((float)Screen.width / Scale - num2) / 2f, 70f, num2, num9);
			float num10 = ((raisedCount > 0) ? Mathf.Abs(Mathf.Sin(Time.realtimeSinceStartup * 4f)) : 0f);
			Color backgroundColor = GUI.backgroundColor;
			Color color = GUI.color;
			GUI.backgroundColor = (Color)((raisedCount > 0) ? Color.Lerp(new Color(0.24f, 0.05f, 0.07f, 0.95f), new Color(0.48f, 0.07f, 0.08f, 0.97f), num10) : new Color(0.16f, 0.09f, 0.11f, 0.93f));
			GUI.Box(bannerRect, "", bannerStyle);
			GUI.backgroundColor = backgroundColor;
			GUI.color = (Color)((raisedCount > 0) ? Color.Lerp(new Color(1f, 0.25f, 0.2f, 0.8f), new Color(1f, 0.45f, 0.35f, 1f), num10) : new Color(0.75f, 0.35f, 0.35f, 0.7f));
			GUI.DrawTexture(new Rect(((Rect)(ref bannerRect)).x, ((Rect)(ref bannerRect)).y, 4f, ((Rect)(ref bannerRect)).height), (Texture)(object)Texture2D.whiteTexture);
			GUI.color = color;
			GUILayout.BeginArea(new Rect(((Rect)(ref bannerRect)).x + 8f, ((Rect)(ref bannerRect)).y + 8f, num3, Mathf.Max(num9, num8 + 16f) + 400f));
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			string text2 = ((raisedCount > 0) ? string.Format("{0} dashboard alarm{1}", raisedCount, (raisedCount == 1) ? "" : "s") : "Dashboard alarms");
			if (num > 0)
			{
				text2 += $" ({num} snoozed)";
			}
			GUILayout.Label(text2, bannerTitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			if (raisedCount >= 2 && GUILayout.Button("Snooze all", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(button, "Snooze all")) }))
			{
				AlarmManager.SnoozeAllRaised();
			}
			if (GUILayout.Button("List", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(button, "List")) }))
			{
				ToggleList();
			}
			GUILayout.EndHorizontal();
			GUILayout.Space(6f);
			foreach (KeyValuePair<AlarmDefinition, string> item2 in list)
			{
				AlarmDefinition key = item2.Key;
				if (key == confirmRemove)
				{
					float num11 = num3 - (float)bannerLineStyle.margin.horizontal;
					GUILayout.Label(RemoveQuestion(key), bannerLineStyle, (GUILayoutOption[])(object)new GUILayoutOption[2]
					{
						GUILayout.Width(num11),
						GUILayout.Height(WrappedHeight(bannerLineStyle, RemoveQuestion(key), num11))
					});
					GUILayout.Space(6f);
					GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
					GUILayout.FlexibleSpace();
					if (GUILayout.Button("Delete alarm", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(button, "Delete alarm")) }))
					{
						AlarmManager.Remove(key);
						if (editing == key)
						{
							CloseEditor(discardNew: false);
						}
						confirmRemove = null;
					}
					GUILayout.Space(6f);
					if (GUILayout.Button("Keep", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(button, "Keep")) }))
					{
						confirmRemove = null;
					}
					GUILayout.EndHorizontal();
					GUILayout.Space(6f);
					continue;
				}
				string text3 = RowAction(key);
				float num12 = num3 - RowButtonsWidth(button, key) - 6f;
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				GUILayout.Label(item2.Value, LineStyle(key), (GUILayoutOption[])(object)new GUILayoutOption[2]
				{
					GUILayout.Width(num12),
					GUILayout.Height(WrappedHeight(LineStyle(key), item2.Value, num12))
				});
				GUILayout.Space(6f);
				if (GUILayout.Button(text3, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(button, text3)) }))
				{
					if (key.state == AlarmState.Snoozed)
					{
						AlarmManager.Unsnooze(key);
					}
					else
					{
						AlarmManager.Snooze(key, key.snoozeMinutes);
					}
				}
				GUILayout.Space(6f);
				if (GUILayout.Button("Edit", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(button, "Edit")) }))
				{
					StatPlan val = AlarmManager.ResolvePlan(GameMain.data, key);
					if (val != null)
					{
						OpenEditor(val);
					}
				}
				GUILayout.Space(6f);
				if (GUILayout.Button("Remove...", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(button, "Remove...")) }))
				{
					confirmRemove = key;
				}
				GUILayout.EndHorizontal();
				GUILayout.Space(6f);
			}
			if (shownCount > num4)
			{
				GUILayout.Label($"...and {shownCount - num4} more (List shows all)", bannerLineStyle, Array.Empty<GUILayoutOption>());
			}
			GUILayout.Label(GUIContent.none, GUIStyle.none, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(1f) });
			if ((int)Event.current.type == 7)
			{
				Rect lastRect = GUILayoutUtility.GetLastRect();
				bannerContentH = ((Rect)(ref lastRect)).yMax;
			}
			GUILayout.EndArea();
		}

		private static void Note(string text, GUIStyle style)
		{
			float width = ((Rect)(ref editorRect)).width - (float)GUI.skin.window.padding.horizontal - (float)style.margin.horizontal;
			GUILayout.Label(text, style, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(WrappedHeight(style, text, width)) });
		}

		private static float WrappedHeight(GUIStyle style, string text, float width)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			if (!singleLine.TryGetValue(style, out var value))
			{
				value = new GUIStyle(style)
				{
					wordWrap = false
				};
				singleLine[style] = value;
			}
			float num = style.padding.horizontal;
			float num2 = Mathf.Max(20f, width - num);
			float num3 = value.CalcSize(new GUIContent("Ag")).y - (float)style.padding.vertical;
			float num4 = value.CalcSize(new GUIContent("a a")).x - value.CalcSize(new GUIContent("aa")).x;
			int num5 = 1;
			float num6 = 0f;
			string[] array = (text ?? "").Split(new char[1] { ' ' });
			foreach (string text2 in array)
			{
				if (text2.Length != 0)
				{
					float num7 = value.CalcSize(new GUIContent(text2)).x - num;
					if (num6 > 0f && num6 + num4 + num7 > num2)
					{
						num5++;
						num6 = num7;
					}
					else
					{
						num6 += ((num6 > 0f) ? num4 : 0f) + num7;
					}
				}
			}
			float num8 = (float)num5 * num3 * 1.15f + (float)style.padding.vertical + 2f;
			return Mathf.Max(style.CalcHeight(new GUIContent(text), width), num8);
		}

		private static string RemoveQuestion(AlarmDefinition a)
		{
			return "Delete this alarm? It stops watching " + AlarmManager.Describe(a) + " and won't sound again. The chart stays on your dashboard. To be warned again later, add a new alarm from the chart's menu.";
		}

		private static float RowButtonsWidth(GUIStyle button, AlarmDefinition a)
		{
			float num = ButtonWidth(button, RowAction(a)) + ButtonWidth(button, "Edit") + ButtonWidth(button, "Remove...");
			float num2 = 3 * button.margin.horizontal + bannerLineStyle.margin.horizontal;
			return num + num2 + 18f + 4f;
		}

		private static string RowAction(AlarmDefinition a)
		{
			if (a.state != AlarmState.Snoozed)
			{
				return SnoozeLabel(a);
			}
			return "Unsnooze";
		}

		private static GUIStyle LineStyle(AlarmDefinition a)
		{
			if (a.state != AlarmState.Snoozed)
			{
				return bannerLineStyle;
			}
			return bannerSnoozedStyle;
		}

		private static string FormatDuration(float seconds)
		{
			int num = Mathf.CeilToInt(seconds);
			if (num < 60)
			{
				return $"{num}s";
			}
			return $"{num / 60}:{num % 60:00}";
		}

		private static string SnoozeLabel(AlarmDefinition a)
		{
			return $"Snooze {a.snoozeMinutes:0.#} min";
		}

		private static float ButtonWidth(GUIStyle style, string text)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return style.CalcSize(new GUIContent(text)).x + 12f;
		}

		private static void DrawEditor(int id)
		{
			AlarmDefinition a = editing;
			StatPlan val = AlarmManager.ResolvePlan(GameMain.data, a);
			if (val == null)
			{
				GUILayout.Label("This chart no longer exists.", Array.Empty<GUILayoutOption>());
				if (GUILayout.Button("Close", Array.Empty<GUILayoutOption>()))
				{
					CloseEditor(discardNew: true);
				}
				GUI.DragWindow();
				return;
			}
			Note("Chart: " + val.displayName + "  -  " + StatReader.ItemName(a.itemId) + ", " + StatReader.AreaName(GameMain.data, a.astroFilter), wrapLabel);
			GUILayout.Space(4f);
			a.enabled = GameSkin.Toggle(a.enabled, "Alarm enabled");
			GUILayout.Space(4f);
			GUILayout.Label("Watch", GameSkin.Header, Array.Empty<GUILayoutOption>());
			AstroItemProductionStatPlan val2 = (AstroItemProductionStatPlan)(object)((val is AstroItemProductionStatPlan) ? val : null);
			if (val2 != null)
			{
				int num = Array.IndexOf(RateMetrics, a.metric);
				int num2 = Choice((num >= 0) ? num : 0, RateMetricLabels, 3);
				if (RateMetrics[num2] != a.metric)
				{
					a.metric = RateMetrics[num2];
					a.ResetRuntime();
					if (Metrics.NeedsMax(a.metric))
					{
						AlarmManager.RequestRecountSoon();
					}
				}
				string text = StatReader.RateWindowName(val2);
				string text2 = ((val2.timeLevel == 5) ? " (the chart is set to totals, so the alarm uses 1 minute)" : "");
				switch (a.metric)
				{
				case AlarmMetric.MaxProduction:
					Note("The most this area's powered machines can make per minute, counting proliferator: the game's reference rate.", GameSkin.DimLabel);
					break;
				case AlarmMetric.UsePercent:
					Note("Consumption (" + text + " average" + text2 + ") as a % of max production. 90 means you are using 90% of what your machines can make.", GameSkin.DimLabel);
					break;
				default:
					Note("Uses the chart's " + text + " average" + text2 + ", the same number the chart shows.", GameSkin.DimLabel);
					break;
				}
			}
			else
			{
				a.metric = AlarmMetric.Stock;
				GUILayout.Label("  Stock (total items in storage, as the chart shows)", Array.Empty<GUILayoutOption>());
			}
			GUILayout.Space(4f);
			GUILayout.Label("Trigger", GameSkin.Header, Array.Empty<GUILayoutOption>());
			AlarmTrigger alarmTrigger = (AlarmTrigger)Choice((int)a.trigger, new string[3] { "Below", "Above", "% drop from average" }, 3);
			if (alarmTrigger != a.trigger)
			{
				a.trigger = alarmTrigger;
				a.ResetRuntimeTimersOnly();
			}
			if (a.trigger == AlarmTrigger.DropPercent)
			{
				Row("Drop %", ref dropText, delegate(double v)
				{
					a.dropPercent = Math.Max(0.1, Math.Min(100.0, v));
				});
				Row("Average over (minutes)", ref averageText, delegate(double v)
				{
					a.averageMinutes = (float)Math.Max(0.5, v);
				});
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				GUILayout.Label("The average freezes while a drop is in progress.", GameSkin.DimLabel, Array.Empty<GUILayoutOption>());
				if (GUILayout.Button("Reset average", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(GUI.skin.button, "Reset average")) }))
				{
					a.history.Clear();
					a.lastAverage = double.NaN;
					a.ResetRuntimeTimersOnly();
				}
				GUILayout.EndHorizontal();
			}
			else
			{
				Row((a.metric == AlarmMetric.Stock) ? "Threshold (items)" : ((a.metric == AlarmMetric.UsePercent) ? "Threshold (%)" : "Threshold (per minute)"), ref thresholdText, delegate(double v)
				{
					a.threshold = v;
				});
			}
			Row("Hold time (seconds)", ref holdText, delegate(double v)
			{
				a.holdSeconds = (float)Math.Max(0.0, v);
			});
			GUILayout.Space(4f);
			a.playSound = GameSkin.Toggle(a.playSound, "Play sound");
			if (a.playSound)
			{
				Note("Sounds (pick one or more; they play together)", GameSkin.DimLabel);
				int length = Sounds.Options.GetLength(0);
				for (int num3 = 0; num3 < length; num3++)
				{
					if (num3 % 3 == 0)
					{
						GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
					}
					string item = Sounds.Options[num3, 0];
					bool flag = a.sounds.Contains(item);
					if (ChoiceButton(flag, Sounds.Options[num3, 1]))
					{
						if (flag)
						{
							a.sounds.Remove(item);
						}
						else
						{
							a.sounds.Add(item);
							a.sounds.Sort((string x, string y) => SoundIndex(x).CompareTo(SoundIndex(y)));
						}
					}
					if (num3 % 3 == 2 || num3 == length - 1)
					{
						GUILayout.EndHorizontal();
					}
				}
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				if (a.sounds.Count == 0)
				{
					GUILayout.Label("No sound picked: the alarm will be silent.", GameSkin.DimLabel, Array.Empty<GUILayoutOption>());
				}
				GUILayout.FlexibleSpace();
				GUI.enabled = a.sounds.Count > 0;
				if (GUILayout.Button("Test", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }))
				{
					AlarmManager.PlaySounds(a.sounds, diagnose: true);
				}
				GUI.enabled = true;
				GUILayout.EndHorizontal();
				Row("Repeat sound every (s, 0 = once)", ref repeatText, delegate(double v)
				{
					a.repeatSoundSeconds = (float)Math.Max(0.0, v);
				});
			}
			Row("Snooze length (minutes)", ref snoozeText, delegate(double v)
			{
				a.snoozeMinutes = (float)Math.Max(0.1, v);
			});
			GUILayout.Space(6f);
			string text3 = ((a.trigger == AlarmTrigger.DropPercent) ? ("   average " + AlarmManager.FormatValue(a, a.lastAverage)) : "");
			string text4 = ((a.metric == AlarmMetric.UsePercent && a.hasMax) ? ("   (max production " + AlarmManager.Format(a.lastMax) + "/min)") : "");
			if (Metrics.NeedsRecount(a.metric) && !a.hasValue)
			{
				Note("Now: waiting for the game to count machines and storage (a few seconds)...", GameSkin.DimLabel);
			}
			else
			{
				Note($"Now: {AlarmManager.FormatValue(a, a.lastValue)}{text4}{text3}   state: {a.state}", wrapLabel);
			}
			GUILayout.Space(6f);
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (GUILayout.Button(editingIsNew ? "Create" : "Done", Array.Empty<GUILayoutOption>()))
			{
				a.isDraft = false;
				a.ResetRuntimeTimersOnly();
				CloseEditor(discardNew: false);
			}
			if (!editingIsNew && GUILayout.Button("Delete alarm", Array.Empty<GUILayoutOption>()))
			{
				AlarmManager.Remove(a);
				CloseEditor(discardNew: false);
			}
			if (GUILayout.Button(editingIsNew ? "Cancel" : "Close", Array.Empty<GUILayoutOption>()))
			{
				CloseEditor(discardNew: true);
			}
			GUILayout.EndHorizontal();
			GUI.DragWindow();
		}

		private static int SoundIndex(string sound)
		{
			for (int i = 0; i < Sounds.Options.GetLength(0); i++)
			{
				if (Sounds.Options[i, 0] == sound)
				{
					return i;
				}
			}
			return int.MaxValue;
		}

		private static int Choice(int current, string[] labels, int perRow)
		{
			int result = current;
			for (int i = 0; i < labels.Length; i++)
			{
				if (i % perRow == 0)
				{
					GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				}
				if (ChoiceButton(i == current, labels[i]))
				{
					result = i;
				}
				if (i % perRow == perRow - 1 || i == labels.Length - 1)
				{
					GUILayout.EndHorizontal();
				}
			}
			return result;
		}

		private static bool ChoiceButton(bool on, string label)
		{
			return GUILayout.Button(label, on ? GameSkin.SelectedButton : GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.MinWidth(120f) });
		}

		private static void Row(string label, ref string text, Action<double> apply)
		{
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label(label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(230f) });
			string text2 = GUILayout.TextField(text, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) });
			GUILayout.EndHorizontal();
			if (text2 != text)
			{
				text = text2;
				if (TryParse(text2, out var value))
				{
					apply(value);
				}
			}
		}

		public static bool TryParse(string s, out double value)
		{
			value = 0.0;
			if (string.IsNullOrWhiteSpace(s))
			{
				return false;
			}
			s = s.Trim().Replace(",", "").Replace("_", "");
			double num = 1.0;
			switch (char.ToLowerInvariant(s[s.Length - 1]))
			{
			case 'k':
				num = 1000.0;
				s = s.Substring(0, s.Length - 1);
				break;
			case 'm':
				num = 1000000.0;
				s = s.Substring(0, s.Length - 1);
				break;
			case 'b':
			case 'g':
				num = 1000000000.0;
				s = s.Substring(0, s.Length - 1);
				break;
			}
			if (!double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return false;
			}
			value = result * num;
			return true;
		}

		private static void DrawList(int id)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			listScroll = GUILayout.BeginScrollView(listScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(280f) });
			if (AlarmManager.Alarms.Count == 0)
			{
				GUILayout.Label("No alarms yet. Open the Dashboard, click a production or storage chart's menu button, and choose \"Add alarm...\".", GameSkin.DimLabel, Array.Empty<GUILayoutOption>());
			}
			AlarmDefinition alarmDefinition = null;
			foreach (AlarmDefinition alarm in AlarmManager.Alarms)
			{
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				bool flag = GameSkin.Toggle(alarm.enabled, "", GUILayout.Width(22f));
				if (flag != alarm.enabled)
				{
					alarm.enabled = flag;
					alarm.ResetRuntimeTimersOnly();
				}
				GUILayout.Label($"[{alarm.state}] {AlarmManager.Describe(alarm)} - now {AlarmManager.FormatValue(alarm, alarm.lastValue)}", wrapLabel, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
				if (alarm.IsRaised && GUILayout.Button("Snooze", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(GUI.skin.button, "Snooze")) }))
				{
					AlarmManager.Snooze(alarm, alarm.snoozeMinutes);
				}
				if (alarm.state == AlarmState.Snoozed && GUILayout.Button("Unsnooze", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(GUI.skin.button, "Unsnooze")) }))
				{
					AlarmManager.Unsnooze(alarm);
				}
				if (GUILayout.Button("Edit", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(GUI.skin.button, "Edit")) }))
				{
					StatPlan val = AlarmManager.ResolvePlan(GameMain.data, alarm);
					if (val != null)
					{
						OpenEditor(val);
					}
				}
				if (GUILayout.Button("Delete", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(ButtonWidth(GUI.skin.button, "Delete")) }))
				{
					alarmDefinition = alarm;
				}
				GUILayout.EndHorizontal();
			}
			if (alarmDefinition != null)
			{
				if (editing == alarmDefinition)
				{
					CloseEditor(discardNew: false);
				}
				AlarmManager.Remove(alarmDefinition);
			}
			GUILayout.EndScrollView();
			if (GUILayout.Button("Close", Array.Empty<GUILayoutOption>()))
			{
				listOpen = false;
			}
			GUI.DragWindow();
		}
	}
	internal static class GameSkin
	{
		public static readonly Color Text = new Color(0.86f, 0.92f, 0.96f, 1f);

		public static readonly Color TextDim = new Color(0.62f, 0.7f, 0.76f, 1f);

		public static readonly Color Accent = new Color(0.38f, 0.84f, 1f, 1f);

		private static readonly Color Panel = new Color(0.06f, 0.11f, 0.16f, 0.94f);

		private static readonly Color TitleBand = new Color(0.11f, 0.19f, 0.26f, 0.97f);

		private static readonly Color Edge = new Color(0.38f, 0.84f, 1f, 0.35f);

		private static readonly Color ButtonFill = new Color(0.16f, 0.25f, 0.33f, 0.95f);

		private static readonly Color ButtonHover = new Color(0.22f, 0.35f, 0.45f, 0.98f);

		private static readonly Color ButtonPressed = new Color(0.12f, 0.42f, 0.56f, 1f);

		private static readonly Color SelectedFill = new Color(0.14f, 0.5f, 0.68f, 1f);

		private static readonly Color FieldFill = new Color(0.03f, 0.07f, 0.1f, 0.95f);

		private static readonly Color FieldEdge = new Color(0.3f, 0.4f, 0.48f, 1f);

		private static GUISkin skin;

		private static readonly List<Texture2D> textures = new List<Texture2D>();

		public static GUIStyle SelectedButton { get; private set; }

		public static GUIStyle Check { get; private set; }

		public static GUIStyle DimLabel { get; private set; }

		public static GUIStyle Header { get; private set; }

		public static Texture2D CheckOn { get; private set; }

		public static Texture2D CheckOff { get; private set; }

		public static Texture2D BannerFill { get; private set; }

		public static Font GameFont { get; private set; }

		public static GUISkin Skin
		{
			get
			{
				if ((Object)(object)skin == (Object)null)
				{
					Build();
				}
				return skin;
			}
		}

		private static void Build()
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Expected O, but got Unknown
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Expected O, but got Unknown
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Expected O, but got Unknown
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Expected O, but got Unknown
			//IL_01ab: Expected O, but got Unknown
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0308: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Expected O, but got Unknown
			//IL_0319: Unknown result type (might be due to invalid IL or missing references)
			//IL_0323: Expected O, but got Unknown
			//IL_0333: Unknown result type (might be due to invalid IL or missing references)
			//IL_0338: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Expected O, but got Unknown
			//IL_0344: Unknown result type (might be due to invalid IL or missing references)
			//IL_0349: Unknown result type (might be due to invalid IL or missing references)
			//IL_0382: Unknown result type (might be due to invalid IL or missing references)
			//IL_0387: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03de: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0425: Unknown result type (might be due to invalid IL or missing references)
			//IL_043a: Unknown result type (might be due to invalid IL or missing references)
			//IL_043f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0477: Unknown result type (might be due to invalid IL or missing references)
			//IL_0487: Unknown result type (might be due to invalid IL or missing references)
			//IL_0497: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b0: Expected O, but got Unknown
			//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bf: Expected O, but got Unknown
			//IL_04c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0516: Unknown result type (might be due to invalid IL or missing references)
			//IL_0520: Expected O, but got Unknown
			//IL_0584: Unknown result type (might be due to invalid IL or missing references)
			//IL_0589: Unknown result type (might be due to invalid IL or missing references)
			//IL_0590: Unknown result type (might be due to invalid IL or missing references)
			//IL_0597: Unknown result type (might be due to invalid IL or missing references)
			//IL_059c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a6: Expected O, but got Unknown
			//IL_05ab: Expected O, but got Unknown
			//IL_05b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_061b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0625: Expected O, but got Unknown
			//IL_0634: Unknown result type (might be due to invalid IL or missing references)
			//IL_0639: Unknown result type (might be due to invalid IL or missing references)
			//IL_066a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0674: Expected O, but got Unknown
			skin = Object.Instantiate<GUISkin>(GUI.skin);
			((Object)skin).hideFlags = (HideFlags)61;
			GameFont = FindGameFont();
			if ((Object)(object)GameFont != (Object)null)
			{
				skin.font = GameFont;
			}
			skin.settings.cursorColor = Accent;
			skin.settings.selectionColor = new Color(Accent.r, Accent.g, Accent.b, 0.35f);
			GUIStyle window = skin.window;
			Texture2D tex = Make(16, 40, delegate(int x, int top, int w, int h)
			{
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				if (x == 0 || x == w - 1 || top == 0 || top == h - 1)
				{
					return Edge;
				}
				if (top < 26)
				{
					return TitleBand;
				}
				return (Color)((top == 26) ? new Color(Accent.r, Accent.g, Accent.b, 0.7f) : Panel);
			});
			SetAll(window, tex, Accent);
			window.border = new RectOffset(2, 2, 28, 2);
			window.padding = new RectOffset(12, 12, 36, 12);
			window.contentOffset = new Vector2(0f, -30f);
			window.alignment = (TextAnchor)1;
			window.fontSize = 15;
			window.fontStyle = (FontStyle)1;
			skin.label.normal.textColor = Text;
			skin.label.fontSize = 14;
			DimLabel = new GUIStyle(skin.label)
			{
				wordWrap = true,
				fontSize = 13
			};
			DimLabel.normal.textColor = TextDim;
			Header = new GUIStyle(skin.label)
			{
				fontStyle = (FontStyle)1,
				fontSize = 14,
				margin = new RectOffset(4, 4, 6, 2)
			};
			Header.normal.textColor = Accent;
			GUIStyle button = skin.button;
			button.normal.background = Boxed(ButtonFill, Edge);
			button.hover.background = Boxed(ButtonHover, new Color(Accent.r, Accent.g, Accent.b, 0.7f));
			button.active.background = Boxed(ButtonPressed, Accent);
			button.focused.background = button.normal.background;
			button.onNormal.background = button.normal.background;
			button.onHover.background = button.hover.background;
			button.onActive.background = button.active.background;
			button.normal.textColor = Text;
			button.hover.textColor = Color.white;
			button.active.textColor = Color.white;
			button.focused.textColor = Text;
			button.onNormal.textColor = Text;
			button.onHover.textColor = Color.white;
			button.onActive.textColor = Color.white;
			button.border = new RectOffset(2, 2, 2, 2);
			button.padding = new RectOffset(10, 10, 5, 5);
			button.fontSize = 14;
			button.alignment = (TextAnchor)4;
			SelectedButton = new GUIStyle(button)
			{
				fontStyle = (FontStyle)1
			};
			Texture2D background = Boxed(SelectedFill, Accent);
			SelectedButton.normal.background = background;
			SelectedButton.hover.background = Boxed(new Color(0.18f, 0.58f, 0.78f, 1f), Accent);
			SelectedButton.active.background = background;
			SelectedButton.normal.textColor = Color.white;
			SelectedButton.hover.textColor = Color.white;
			GUIStyle textField = skin.textField;
			Texture2D background2 = Boxed(FieldFill, FieldEdge);
			textField.normal.background = background2;
			textField.hover.background = Boxed(FieldFill, new Color(Accent.r, Accent.g, Accent.b, 0.6f));
			textField.focused.background = Boxed(FieldFill, Accent);
			textField.active.background = textField.focused.background;
			textField.onNormal.background = background2;
			textField.normal.textColor = Text;
			textField.hover.textColor = Text;
			textField.focused.textColor = Color.white;
			textField.border = new RectOffset(2, 2, 2, 2);
			textField.padding = new RectOffset(6, 6, 4, 4);
			textField.fontSize = 14;
			BannerFill = Boxed(Color.white, new Color(1f, 0.55f, 0.5f, 1f));
			SetAll(skin.box, BannerFill, Text);
			skin.box.border = new RectOffset(2, 2, 2, 2);
			CheckOff = Make(16, 16, (int x, int top, int w, int h) => (!Edge1(x, top, w, h)) ? FieldFill : Accent);
			CheckOn = Make(16, 16, (int x, int top, int w, int h) => (!Edge1(x, top, w, h)) ? ((x < 4 || x > 11 || top < 4 || top > 11) ? FieldFill : Accent) : Accent);
			Check = new GUIStyle(skin.label)
			{
				imagePosition = (ImagePosition)0,
				alignment = (TextAnchor)3,
				padding = new RectOffset(0, 4, 3, 3)
			};
			Check.hover.textColor = Color.white;
			skin.verticalScrollbar.normal.background = Make(4, 4, (int x, int top, int w, int h) => FieldFill);
			skin.verticalScrollbar.fixedWidth = 10f;
			skin.verticalScrollbar.border = new RectOffset(0, 0, 0, 0);
			skin.verticalScrollbarThumb.normal.background = Boxed(ButtonHover, Edge);
			skin.verticalScrollbarThumb.fixedWidth = 10f;
			skin.verticalScrollbarThumb.border = new RectOffset(2, 2, 2, 2);
			skin.verticalScrollbarUpButton.fixedHeight = 0f;
			skin.verticalScrollbarDownButton.fixedHeight = 0f;
			skin.scrollView.normal.background = null;
		}

		public static bool Toggle(bool value, string label, params GUILayoutOption[] options)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			if (!GUILayout.Button(new GUIContent(string.IsNullOrEmpty(label) ? "" : ("  " + label), (Texture)(object)(value ? CheckOn : CheckOff)), Check, options))
			{
				return value;
			}
			return !value;
		}

		private static Font FindGameFont()
		{
			try
			{
				if ((Object)(object)UIRoot.instance == (Object)null)
				{
					return null;
				}
				Dictionary<Font, int> dictionary = new Dictionary<Font, int>();
				Text[] componentsInChildren = ((Component)UIRoot.instance).GetComponentsInChildren<Text>(true);
				foreach (Text val in componentsInChildren)
				{
					if (!((Object)(object)val.font == (Object)null) && !(((Object)val.font).name == "Arial"))
					{
						dictionary.TryGetValue(val.font, out var value);
						dictionary[val.font] = value + 1;
					}
				}
				Font val2 = null;
				int num = 0;
				foreach (KeyValuePair<Font, int> item in dictionary)
				{
					if (item.Value > num)
					{
						val2 = item.Key;
						num = item.Value;
					}
				}
				if ((Object)(object)val2 != (Object)null)
				{
					ManualLogSource log = Plugin.Log;
					if (log != null)
					{
						log.LogInfo((object)("Alarm windows use the game font '" + ((Object)val2).name + "'"));
					}
				}
				return val2;
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("Could not find the game's UI font: " + ex.Message));
				}
				return null;
			}
		}

		private static bool Edge1(int x, int top, int w, int h)
		{
			if (x != 0 && x != w - 1 && top != 0)
			{
				return top == h - 1;
			}
			return true;
		}

		private static void SetAll(GUIStyle s, Texture2D tex, Color text)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			s.normal.background = tex;
			s.hover.background = tex;
			s.active.background = tex;
			s.focused.background = tex;
			s.onNormal.background = tex;
			s.onHover.background = tex;
			s.onActive.background = tex;
			s.onFocused.background = tex;
			s.normal.textColor = text;
			s.hover.textColor = text;
			s.active.textColor = text;
			s.focused.textColor = text;
			s.onNormal.textColor = text;
			s.onHover.textColor = text;
			s.onActive.textColor = text;
			s.onFocused.textColor = text;
		}

		private static Texture2D Boxed(Color fill, Color edge)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			return Make(8, 8, (int x, int top, int w, int h) => (!Edge1(x, top, w, h)) ? fill : edge);
		}

		private static Texture2D Make(int w, int h, Func<int, int, int, int, Color> colorAt)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(w, h, (TextureFormat)4, false)
			{
				filterMode = (FilterMode)0,
				wrapMode = (TextureWrapMode)1,
				hideFlags = (HideFlags)61
			};
			Color[] array = (Color[])(object)new Color[w * h];
			for (int i = 0; i < h; i++)
			{
				for (int j = 0; j < w; j++)
				{
					array[(h - 1 - i) * w + j] = colorAt(j, i, w, h);
				}
			}
			val.SetPixels(array);
			val.Apply();
			textures.Add(val);
			return val;
		}
	}
	public static class InputBlocker
	{
		private static readonly List<RectTransform> blockers = new List<RectTransform>();

		private static Canvas canvas;

		public static void Sync(IList<Rect> guiRects, float scale)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			if (!EnsureCanvas())
			{
				return;
			}
			for (int i = 0; i < guiRects.Count; i++)
			{
				RectTransform val = ((i < blockers.Count) ? blockers[i] : Create());
				if ((Object)(object)val == (Object)null)
				{
					blockers.Clear();
					canvas = null;
					return;
				}
				Place(val, guiRects[i], scale);
			}
			for (int j = guiRects.Count; j < blockers.Count; j++)
			{
				if ((Object)(object)blockers[j] != (Object)null && ((Component)blockers[j]).gameObject.activeSelf)
				{
					((Component)blockers[j]).gameObject.SetActive(false);
				}
			}
		}

		public static void HideAll()
		{
			foreach (RectTransform blocker in blockers)
			{
				if ((Object)(object)blocker != (Object)null && ((Component)blocker).gameObject.activeSelf)
				{
					((Component)blocker).gameObject.SetActive(false);
				}
			}
		}

		private static bool EnsureCanvas()
		{
			if ((Object)(object)canvas != (Object)null)
			{
				return true;
			}
			blockers.Clear();
			UIGame val = (((Object)(object)UIRoot.instance != (Object)null) ? UIRoot.instance.uiGame : null);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			Canvas componentInParent = ((Component)val).GetComponentInParent<Canvas>();
			canvas = (((Object)(object)componentInParent != (Object)null) ? componentInParent.rootCanvas : null);
			return (Object)(object)canvas != (Object)null;
		}

		private static RectTransform Create()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("dashboard-alarm-input-blocker", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			RectTransform val2 = (RectTransform)val.transform;
			((Transform)val2).SetParent(((Component)canvas).transform, false);
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor(0.5f, 0.5f);
			val2.anchorMax = val3;
			val2.anchorMin = val3;
			val2.pivot = new Vector2(0.5f, 0.5f);
			Image component = val.GetComponent<Image>();
			((Graphic)component).color = new Color(0f, 0f, 0f, 0f);
			((Graphic)component).raycastTarget = true;
			blockers.Add(val2);
			return val2;
		}

		private static void Place(RectTransform rt, Rect gui, float scale)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			if (!((Component)rt).gameObject.activeSelf)
			{
				((Component)rt).gameObject.SetActive(true);
			}
			((Transform)rt).SetAsLastSibling();
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(((Rect)(ref gui)).xMin * scale, (float)Screen.height - ((Rect)(ref gui)).yMax * scale);
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(((Rect)(ref gui)).xMax * scale, (float)Screen.height - ((Rect)(ref gui)).yMin * scale);
			RectTransform val3 = (RectTransform)((Component)canvas).transform;
			Camera val4 = (((int)canvas.renderMode == 0) ? null : canvas.worldCamera);
			Vector2 val5 = default(Vector2);
			RectTransformUtility.ScreenPointToLocalPointInRectangle(val3, val, val4, ref val5);
			Vector2 val6 = default(Vector2);
			RectTransformUtility.ScreenPointToLocalPointInRectangle(val3, val2, val4, ref val6);
			((Transform)rt).localPosition = new Vector3((val5.x + val6.x) / 2f, (val5.y + val6.y) / 2f, 0f);
			rt.sizeDelta = new Vector2(Mathf.Abs(val6.x - val5.x), Mathf.Abs(val6.y - val5.y));
		}
	}
	public static class OptionsToggle
	{
		private const string CheckboxLabel = "Dashboard alarms play with sound off";

		private const string VolumeLabel = "Dashboard alarm volume";

		private const string TestLabel = "Test";

		private const string NoteText = "The two options above are added by the DashboardAlarms mod.";

		private static UIToggle toggle;

		private static Slider volumeSlider;

		private static Text volumeValueText;

		private static bool attempted;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIOptionWindow), "_OnCreate")]
		public static void UIOptionWindow_OnCreate_Postfix(UIOptionWindow __instance)
		{
			TryBuild(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIOptionWindow), "_OnOpen")]
		public static void UIOptionWindow_OnOpen_Postfix(UIOptionWindow __instance)
		{
			if ((Object)(object)toggle == (Object)null && !attempted)
			{
				TryBuild(__instance);
			}
			if ((Object)(object)toggle != (Object)null)
			{
				toggle.isOn = Plugin.PlayWithSoundOff;
			}
			if ((Object)(object)volumeSlider != (Object)null)
			{
				volumeSlider.value = Plugin.AlarmVolumePercent;
				RefreshVolumeText();
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(UIOptionWindow), "OnApplyClick")]
		public static void UIOptionWindow_OnApplyClick_Prefix(UIOptionWindow __instance)
		{
			if (!((Object)(object)__instance.applyButton == (Object)null) && ((Selectable)__instance.applyButton.button).interactable)
			{
				bool playWithSoundOff = (((Object)(object)toggle != (Object)null) ? toggle.isOn : Plugin.PlayWithSoundOff);
				int volumePercent = (((Object)(object)volumeSlider != (Object)null) ? Mathf.RoundToInt(volumeSlider.value) : Plugin.AlarmVolumePercent);
				Plugin.SetSoundOptions(playWithSoundOff, volumePercent);
			}
		}

		private static void TryBuild(UIOptionWindow window)
		{
			attempted = true;
			try
			{
				Build(window);
			}
			catch (Exception ex)
			{
				toggle = null;
				volumeSlider = null;
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Could not add the alarm sound options to Settings > Audio (the config file settings still work): " + ex));
				}
			}
		}

		private static void Build(UIOptionWindow window)
		{
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Expected O, but got Unknown
			//IL_04b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_04db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0379: Unknown result type (might be due to invalid IL or missing references)
			//IL_0383: Expected O, but got Unknown
			//IL_03fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0405: Expected O, but got Unknown
			UIToggle backgroundMuteComp = window.backgroundMuteComp;
			if ((Object)(object)backgroundMuteComp == (Object)null)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"Settings window has no background-mute checkbox to copy; alarm sound options not added");
				}
				return;
			}
			Transform parent = ((Component)backgroundMuteComp).transform.parent;
			Transform val = (((Object)(object)parent != (Object)null) ? parent.parent : null);
			Transform val2 = (((Object)(object)val != (Object)null) ? FindLabelColumn(val, parent) : null);
			LogLayout(val2, parent);
			if ((Object)(object)parent == (Object)null || (Object)(object)val2 == (Object)null)
			{
				ManualLogSource log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)"Settings > Audio layout is not as expected; alarm sound options not added (see layout above)");
				}
				return;
			}
			RectTransform val3 = LabelAt(val2, CenterY(((Component)backgroundMuteComp).transform));
			if ((Object)(object)val3 == (Object)null)
			{
				ManualLogSource log3 = Plugin.Log;
				if (log3 != null)
				{
					log3.LogWarning((object)"Could not find the label of the background-mute row; alarm sound options not added");
				}
				return;
			}
			float num = 0f;
			if ((Object)(object)window.combatMusicEnabledComp != (Object)null)
			{
				RectTransform val4 = LabelAt(val2, CenterY(((Component)window.combatMusicEnabledComp).transform));
				if ((Object)(object)val4 != (Object)null && (Object)(object)val4 != (Object)(object)val3)
				{
					num = CenterY((Transform)(object)val3) - CenterY((Transform)(object)val4);
				}
			}
			if (num >= 0f)
			{
				num = TypicalStep(val2);
			}
			float num2 = float.MaxValue;
			foreach (Transform item in val2)
			{
				Transform val5 = item;
				if (((Component)val5).gameObject.activeSelf)
				{
					num2 = Mathf.Min(num2, CenterY(val5));
				}
			}
			float dy = num2 + num - CenterY((Transform)(object)val3);
			CloneLabel((Transform)(object)val3, val2, "dashboard-alarms-play-with-sound-off", "Dashboard alarms play with sound off", dy);
			toggle = ((Component)CloneAt(ControlRoot(((Component)backgroundMuteComp).transform, parent), parent, "dashboard-alarms-play-with-sound-off", dy)).GetComponentInChildren<UIToggle>(true);
			if ((Object)(object)toggle != (Object)null)
			{
				toggle.toggle.onValueChanged = new ToggleEvent();
				toggle.isOn = Plugin.PlayWithSoundOff;
			}
			Slider dfAttackAlertvolumeComp = window.dfAttackAlertvolumeComp;
			if ((Object)(object)dfAttackAlertvolumeComp != (Object)null)
			{
				RectTransform val6 = (((Object)(object)window.dfAttackAlertVolumeLabel != (Object)null && (Object)(object)((Transform)window.dfAttackAlertVolumeLabel).parent == (Object)(object)val2) ? window.dfAttackAlertVolumeLabel : LabelAt(val2, CenterY(((Component)dfAttackAlertvolumeComp).transform)));
				float num3 = CenterY((Transform)(((Object)(object)val6 != (Object)null) ? ((object)val6) : ((object)((Component)dfAttackAlertvolumeComp).transform)));
				dy = num2 + 2f * num - num3;
				if ((Object)(object)val6 != (Object)null)
				{
					CloneLabel((Transform)(object)val6, val2, "dashboard-alarms-volume", "Dashboard alarm volume", dy);
				}
				Transform val7 = ControlRoot(((Component)dfAttackAlertvolumeComp).transform, parent);
				Transform copy = CloneAt(val7, parent, "dashboard-alarms-volume", dy);
				Transform obj = FindCopy(val7, copy, ((Component)dfAttackAlertvolumeComp).transform);
				volumeSlider = ((obj != null) ? ((Component)obj).GetComponent<Slider>() : null);
				Text dfAttackAlertvolumeComp2 = window.dfAttackAlertvolumeComp1;
				if ((Object)(object)dfAttackAlertvolumeComp2 != (Object)null)
				{
					Transform val8 = FindCopy(val7, copy, ((Component)dfAttackAlertvolumeComp2).transform);
					if ((Object)(object)val8 != (Object)null)
					{
						volumeValueText = ((Component)val8).GetComponent<Text>();
					}
					else
					{
						Transform val9 = ControlRoot(((Component)dfAttackAlertvolumeComp2).transform, parent);
						if ((Object)(object)val9 != (Object)null && (Object)(object)val9 != (Object)(object)val7)
						{
							Transform copy2 = CloneAt(val9, parent, "dashboard-alarms-volume-value", dy);
							Transform obj2 = FindCopy(val9, copy2, ((Component)dfAttackAlertvolumeComp2).transform);
							volumeValueText = ((obj2 != null) ? ((Component)obj2).GetComponent<Text>() : null);
						}
					}
				}
				if ((Object)(object)volumeSlider != (Object)null)
				{
					volumeSlider.onValueChanged = new SliderEvent();
					volumeSlider.minValue = 0f;
					volumeSlider.maxValue = 100f;
					volumeSlider.wholeNumbers = true;
					volumeSlider.value = Plugin.AlarmVolumePercent;
					((UnityEvent<float>)(object)volumeSlider.onValueChanged).AddListener((UnityAction<float>)delegate
					{
						RefreshVolumeText();
					});
					RefreshVolumeText();
					AddTestButton(window, parent, (RectTransform)((Component)volumeSlider).transform);
				}
			}
			else
			{
				ManualLogSource log4 = Plugin.Log;
				if (log4 != null)
				{
					log4.LogWarning((object)"Settings > Audio has no alert-volume slider to copy; alarm volume slider not added (config AlarmVolumePercent still works)");
				}
			}
			dy = num2 + 3f * num - CenterY((Transform)(object)val3);
			RectTransform val10 = CloneLabel((Transform)(object)val3, val2, "dashboard-alarms-note", "The two options above are added by the DashboardAlarms mod.", dy);
			for (int num4 = ((Transform)val10).childCount - 1; num4 >= 0; num4--)
			{
				Object.DestroyImmediate((Object)(object)((Component)((Transform)val10).GetChild(num4)).gameObject);
			}
			Text component = ((Component)val10).GetComponent<Text>();
			if ((Object)(object)component != (Object)null)
			{
				component.fontSize = Mathf.Max(10, Mathf.RoundToInt((float)component.fontSize * 0.8f));
				component.fontStyle = (FontStyle)2;
				Color color = ((Graphic)component).color;
				((Graphic)component).color = new Color(color.r, color.g, color.b, color.a * 0.6f);
				component.horizontalOverflow = (HorizontalWrapMode)1;
			}
			GrowScrollContent(val, -3f * num);
			ManualLogSource log5 = Plugin.Log;
			if (log5 != null)
			{
				log5.LogInfo((object)($"Added dashboard alarm sound options to Settings > Audio (row step {num:0.###}); " + "checkbox " + (((Object)(object)toggle != (Object)null) ? "ok" : "missing") + ", slider " + (((Object)(object)volumeSlider != (Object)null) ? "ok" : "missing") + ", value text " + (((Object)(object)volumeValueText != (Object)null) ? "ok" : "missing")));
			}
		}

		private static Transform ControlRoot(Transform t, Transform column)
		{
			while ((Object)(object)t != (Object)null)
			{
				if ((Object)(object)t.parent == (Object)(object)column)
				{
					return t;
				}
				t = t.parent;
			}
			return null;
		}

		private static Transform FindCopy(Transform root, Transform copy, Transform target)
		{
			string text = PathFrom(root, target);
			if (text == null)
			{
				return null;
			}
			if (text.Length != 0)
			{
				return copy.Find(text);
			}
			return copy;
		}

		private static Transform FindLabelColumn(Transform container, Transform comps)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			Transform val = container.Find("labels");
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			Transform result = null;
			int num = 0;
			foreach (Transform item in container)
			{
				Transform val2 = item;
				if ((Object)(object)val2 == (Object)(object)comps)
				{
					continue;
				}
				int num2 = 0;
				foreach (Transform item2 in val2)
				{
					if ((Object)(object)((Component)item2).GetComponent<Text>() != (Object)null)
					{
						num2++;
					}
				}
				if (num2 > num)
				{
					result = val2;
					num = num2;
				}
			}
			return result;
		}

		private static RectTransform LabelAt(Transform labels, float y)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			RectTransform result = null;
			float num = float.MaxValue;
			foreach (Transform label in labels)
			{
				Transform val = label;
				if (!((Component)val).gameObject.activeSelf)
				{
					continue;
				}
				RectTransform val2 = (RectTransform)(object)((val is RectTransform) ? val : null);
				if (val2 != null)
				{
					float num2 = Mathf.Abs(CenterY((Transform)(object)val2) - y);
					if (num2 < num)
					{
						result = val2;
						num = num2;
					}
				}
			}
			return result;
		}

		private static float TypicalStep(Transform labels)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			List<float> list = new List<float>();
			foreach (Transform label in labels)
			{
				Transform val = label;
				if (((Component)val).gameObject.activeSelf)
				{
					list.Add(CenterY(val));
				}
			}
			list.Sort();
			List<float> list2 = new List<float>();
			for (int i = 1; i < list.Count; i++)
			{
				if (list[i] - list[i - 1] > 0.0001f)
				{
					list2.Add(list[i] - list[i - 1]);
				}
			}
			if (list2.Count == 0)
			{
				return -0.4f;
			}
			list2.Sort();
			return 0f - list2[list2.Count / 2];
		}

		private static float CenterY(Transform t)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			RectTransform val = (RectTransform)(object)((t is RectTransform) ? t : null);
			if (val != null)
			{
				Rect rect = val.rect;
				return ((Transform)val).TransformPoint(Vector2.op_Implicit(((Rect)(ref rect)).center)).y;
			}
			return t.position.y;
		}

		private static Transform CloneAt(Transform original, Transform parent, string name, float dy)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = Object.Instantiate<GameObject>(((Component)original).gameObject, parent, false);
			((Object)obj).name = name;
			RemoveLocalizers(obj);
			obj.transform.position = original.position + new Vector3(0f, dy, 0f);
			obj.SetActive(true);
			return obj.transform;
		}

		private static RectTransform CloneLabel(Transform original, Transform labels, string name, string text, float dy)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			Transform val = CloneAt(original, labels, name, dy);
			Text val2 = ((Component)val).GetComponent<Text>();
			if ((Object)(object)val2 == (Object)null)
			{
				val2 = ((Component)val).GetComponentInChildren<Text>(true);
			}
			if ((Object)(object)val2 != (Object)null)
			{
				val2.text = text;
			}
			return (RectTransform)val;
		}

		private static void GrowScrollContent(Transform container, float worldHeight)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			ScrollRect componentInParent = ((Component)container).GetComponentInParent<ScrollRect>();
			if (!((Object)(object)componentInParent == (Object)null) && !((Object)(object)componentInParent.content == (Object)null))
			{
				RectTransform content = componentInParent.content;
				float num = Mathf.Abs(((Transform)content).InverseTransformVector(new Vector3(0f, worldHeight, 0f)).y);
				content.sizeDelta = new Vector2(content.sizeDelta.x, content.sizeDelta.y + num);
			}
		}

		private static void AddTestButton(UIOptionWindow window, Transform column, RectTransform slider)
		{
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			UIButton revertAllButton = window.revertAllButton;
			if ((Object)(object)revertAllButton == (Object)null)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"No settings button to copy; Test button not added");
				}
				return;
			}
			GameObject val = Object.Instantiate<GameObject>(((Component)revertAllButton).gameObject, column, false);
			((Object)val).name = "dashboard-alarms-test";
			RemoveLocalizers(val);
			UIButton component = val.GetComponent<UIButton>();
			component.tips.tipTitle = "";
			component.tips.tipText = "";
			component.onClick += delegate
			{
				PlayPreview();
			};
			Text[] componentsInChildren = val.GetComponentsInChildren<Text>(true);
			for (int num = 0; num < componentsInChildren.Length; num++)
			{
				componentsInChildren[num].text = "Test";
			}
			RectTransform val2 = (RectTransform)val.transform;
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			slider.GetWorldCorners(array);
			Vector3 val3 = column.InverseTransformPoint(array[3]);
			Vector3 val4 = column.InverseTransformPoint(array[2]);
			float num2 = Mathf.Abs(val4.y - val3.y);
			Vector2 val5 = default(Vector2);
			((Vector2)(ref val5))..ctor(0.5f, 0.5f);
			val2.anchorMax = val5;
			val2.anchorMin = val5;
			val2.pivot = new Vector2(0f, 0.5f);
			val2.sizeDelta = new Vector2(80f, Mathf.Max(26f, num2 + 10f));
			((Transform)val2).localPosition = new Vector3(val3.x + 16f, (val3.y + val4.y) / 2f, 0f);
		}

		private static void PlayPreview()
		{
			float alarmVolume = (((Object)(object)volumeSlider != (Object)null) ? (volumeSlider.value / 100f) : AlarmManager.AlarmVolume);
			bool playWithSoundOff = (((Object)(object)toggle != (Object)null) ? toggle.isOn : Plugin.PlayWithSoundOff);
			AlarmManager.PlaySound("warning-popup-1", alarmVolume, playWithSoundOff, diagnose: true);
		}

		private static void RefreshVolumeText()
		{
			if (!((Object)(object)volumeValueText == (Object)null) && !((Object)(object)volumeSlider == (Object)null))
			{
				volumeValueText.text = ((volumeSlider.value < 0.5f) ? Localization.Translate("关") : (volumeSlider.value / 100f).ToString("0%"));
			}
		}

		private static void RemoveLocalizers(GameObject go)
		{
			Localizer[] componentsInChildren = go.GetComponentsInChildren<Localizer>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
		}

		private static string PathFrom(Transform root, Transform target)
		{