Decompiled source of VargheimFestival v0.2.6

plugins/VargheimFestival.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.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 VargheimFestival
{
	public enum Kind : byte
	{
		Player,
		Admin,
		Festival
	}
	public sealed class CalEvent
	{
		public int Id;

		public long StartUtc;

		public int Minutes;

		public Kind Kind;

		public string Title = "";

		public string Place = "";

		public string By = "";

		public string ByHost = "";

		public DateTime Start => new DateTime(StartUtc, DateTimeKind.Utc);

		public DateTime End => Start.AddMinutes(Math.Max(0, Minutes));
	}
	public sealed class Holiday
	{
		public string Name = "";

		public int M1;

		public int D1;

		public int M2;

		public int D2;

		public bool Contains(int month, int day)
		{
			int num = month * 100 + day;
			int num2 = M1 * 100 + D1;
			int num3 = M2 * 100 + D2;
			if (num2 > num3)
			{
				if (num < num2)
				{
					return num <= num3;
				}
				return true;
			}
			if (num >= num2)
			{
				return num <= num3;
			}
			return false;
		}

		public DateTime NextStart(DateTime todayLocal)
		{
			for (int i = todayLocal.Year - 1; i <= todayLocal.Year + 1; i++)
			{
				DateTime result = Safe(i, M1, D1);
				if (Safe((M2 * 100 + D2 < M1 * 100 + D1) ? (i + 1) : i, M2, D2).Date >= todayLocal.Date)
				{
					return result;
				}
			}
			return Safe(todayLocal.Year + 1, M1, D1);
		}

		public DateTime EndFor(DateTime start)
		{
			return Safe((M2 * 100 + D2 < M1 * 100 + D1) ? (start.Year + 1) : start.Year, M2, D2);
		}

		private static DateTime Safe(int y, int m, int d)
		{
			return new DateTime(y, m, Math.Min(d, DateTime.DaysInMonth(y, m)));
		}
	}
	public static class Cal
	{
		public const int MaxTitle = 60;

		public const int MaxPlace = 40;

		public static List<Holiday> ParseHolidays(string s, List<string> errors)
		{
			List<Holiday> list = new List<Holiday>();
			string[] array = (s ?? "").Split(';');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length != 0)
				{
					int num = text.IndexOf(' ');
					string obj = ((num > 0) ? text.Substring(0, num) : text);
					string text2 = ((num > 0) ? text.Substring(num + 1).Trim() : "");
					string[] array2 = obj.Split(new string[1] { ".." }, StringSplitOptions.None);
					Holiday holiday = new Holiday
					{
						Name = Clean(text2, 60)
					};
					if (text2.Length == 0 || !Md(array2[0], out holiday.M1, out holiday.D1) || !Md((array2.Length > 1) ? array2[1] : array2[0], out holiday.M2, out holiday.D2))
					{
						errors?.Add("bad holiday '" + text + "' (use MM-DD..MM-DD Name)");
					}
					else
					{
						list.Add(holiday);
					}
				}
			}
			return list;
		}

		private static bool Md(string s, out int m, out int d)
		{
			m = (d = 0);
			string[] array = (s ?? "").Trim().Split('-');
			if (array.Length == 2 && int.TryParse(array[0], out m) && int.TryParse(array[1], out d) && m >= 1 && m <= 12 && d >= 1)
			{
				return d <= 31;
			}
			return false;
		}

		public static string Clean(string s, int max)
		{
			if (string.IsNullOrEmpty(s))
			{
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder(s.Length);
			foreach (char c in s)
			{
				if (c == '<' || c == '>' || c == '$' || c == '\t' || char.IsControl(c))
				{
					stringBuilder.Append((c == '\t') ? ' ' : '\0');
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			string text = stringBuilder.ToString().Replace("\0", "").Trim();
			while (text.Contains("  "))
			{
				text = text.Replace("  ", " ");
			}
			if (text.Length <= max)
			{
				return text;
			}
			return text.Substring(0, max).TrimEnd();
		}

		public static string ToTsv(IEnumerable<CalEvent> evs)
		{
			StringBuilder stringBuilder = new StringBuilder("# VargheimFestival calendar: id, start (UTC ticks), minutes, kind, by, by host, title, place\n");
			foreach (CalEvent ev in evs)
			{
				stringBuilder.Append(ev.Id).Append('\t').Append(ev.StartUtc)
					.Append('\t')
					.Append(ev.Minutes)
					.Append('\t')
					.Append((int)ev.Kind)
					.Append('\t')
					.Append(Clean(ev.By, 40))
					.Append('\t')
					.Append(Clean(ev.ByHost, 80))
					.Append('\t')
					.Append(Clean(ev.Title, 60))
					.Append('\t')
					.Append(Clean(ev.Place, 40))
					.Append('\n');
			}
			return stringBuilder.ToString();
		}

		public static List<CalEvent> FromTsv(string text, List<string> errors)
		{
			List<CalEvent> list = new List<CalEvent>();
			int num = 0;
			string[] array = (text ?? "").Split('\n');
			foreach (string obj in array)
			{
				num++;
				string text2 = obj.TrimEnd('\r');
				if (text2.Length != 0 && text2[0] != '#')
				{
					string[] array2 = text2.Split('\t');
					CalEvent calEvent = new CalEvent();
					if (array2.Length < 8 || !int.TryParse(array2[0], out calEvent.Id) || !long.TryParse(array2[1], out calEvent.StartUtc) || !int.TryParse(array2[2], out calEvent.Minutes) || !int.TryParse(array2[3], out var result) || calEvent.StartUtc <= 0 || calEvent.StartUtc >= DateTime.MaxValue.Ticks)
					{
						errors?.Add("line " + num + " skipped");
						continue;
					}
					calEvent.Kind = (Kind)Math.Max(0, Math.Min(2, result));
					calEvent.By = array2[4];
					calEvent.ByHost = array2[5];
					calEvent.Title = Clean(array2[6], 60);
					calEvent.Place = Clean(array2[7], 40);
					list.Add(calEvent);
				}
			}
			return list;
		}

		public static DateTime SeasonEnd(DateTime nowUtc, DateTime seasonStartUtc, int lengthDays, out int seasonNumber)
		{
			seasonNumber = 1;
			if (lengthDays <= 0)
			{
				return DateTime.MinValue;
			}
			if (nowUtc < seasonStartUtc)
			{
				seasonNumber = 0;
				return seasonStartUtc;
			}
			int num = (int)Math.Floor((nowUtc - seasonStartUtc).TotalDays / (double)lengthDays);
			seasonNumber = num + 1;
			return seasonStartUtc.AddDays((double)(num + 1) * (double)lengthDays);
		}

		public static bool TryParseLocal(string date, string time, out DateTime local)
		{
			string text = (string.IsNullOrEmpty(time) ? "00:00" : time.Trim());
			return DateTime.TryParseExact((date ?? "").Trim() + " " + text, new string[2] { "yyyy-MM-dd HH:mm", "yyyy-MM-dd H:mm" }, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out local);
		}
	}
	internal static class Client
	{
		internal static readonly List<CalEvent> Events = new List<CalEvent>();

		internal static List<Holiday> Holidays = new List<Holiday>();

		internal static DateTime SeasonStartUtc = DateTime.MinValue;

		internal static int SeasonLength;

		internal static int FestivalDays;

		internal static int MaxPerPlayer = 3;

		internal static bool HaveData;

		private static bool s_badPacket;

		private static bool s_asked;

		private static float s_askAt;

		private static MethodInfo s_isAdmin;

		private static bool s_isAdminLooked;

		internal static void Reset()
		{
			HaveData = false;
			s_asked = false;
			s_askAt = Time.time + 3f;
			Events.Clear();
		}

		internal static void Tick()
		{
			if (!s_asked && !HaveData && !(Time.time < s_askAt) && ZRoutedRpc.instance != null && !((Object)(object)ZNet.instance == (Object)null) && !((Object)(object)Player.m_localPlayer == (Object)null))
			{
				s_asked = true;
				ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
				long num = (ZNet.instance.IsServer() ? ZNet.GetUID() : (serverPeer?.m_uid ?? 0));
				if (num != 0L)
				{
					ZRoutedRpc.instance.InvokeRoutedRPC(num, "VFest_CalReq", Array.Empty<object>());
				}
			}
		}

		internal static void OnList(long sender, ZPackage p)
		{
			if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer())
			{
				ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
				if (serverPeer != null && sender != serverPeer.m_uid)
				{
					return;
				}
			}
			try
			{
				byte b = p.ReadByte();
				if (b > 1)
				{
					if (!s_badPacket)
					{
						s_badPacket = true;
						Plugin.Log.LogWarning((object)("Calendar: the server sends packet version " + b + "; update VargheimFestival."));
					}
					return;
				}
				List<Holiday> holidays = Cal.ParseHolidays(p.ReadString(), null);
				long num = p.ReadLong();
				int seasonLength = p.ReadInt();
				int festivalDays = p.ReadInt();
				int maxPerPlayer = p.ReadInt();
				int num2 = p.ReadInt();
				List<CalEvent> list = new List<CalEvent>(Math.Max(0, Math.Min(num2, 2000)));
				for (int i = 0; i < num2 && i < 2000; i++)
				{
					CalEvent calEvent = new CalEvent();
					calEvent.Id = p.ReadInt();
					calEvent.StartUtc = p.ReadLong();
					calEvent.Minutes = p.ReadInt();
					calEvent.Kind = (Kind)Mathf.Clamp(p.ReadInt(), 0, 2);
					calEvent.Title = Cal.Clean(p.ReadString(), 60);
					calEvent.Place = Cal.Clean(p.ReadString(), 40);
					calEvent.By = Cal.Clean(p.ReadString(), 40);
					calEvent.ByHost = p.ReadString();
					if (calEvent.StartUtc > 0 && calEvent.StartUtc < DateTime.MaxValue.Ticks)
					{
						list.Add(calEvent);
					}
				}
				list.Sort((CalEvent a, CalEvent calEvent2) => a.StartUtc.CompareTo(calEvent2.StartUtc));
				Events.Clear();
				Events.AddRange(list);
				Holidays = holidays;
				SeasonStartUtc = ((num > 0) ? new DateTime(num, DateTimeKind.Utc) : DateTime.MinValue);
				SeasonLength = seasonLength;
				FestivalDays = festivalDays;
				MaxPerPlayer = maxPerPlayer;
				if (!HaveData)
				{
					Plugin.Log.LogInfo((object)("Calendar: " + Events.Count + " event(s), " + Holidays.Count + " holiday(s) received."));
				}
				HaveData = true;
				Ui.Dirty();
			}
			catch (Exception ex)
			{
				if (!s_badPacket)
				{
					s_badPacket = true;
					Plugin.Log.LogWarning((object)("Calendar: unreadable list from the server (" + ex.Message + ") - versions differ?"));
				}
			}
		}

		private static long ServerTarget()
		{
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return 0L;
			}
			if (ZNet.instance.IsServer())
			{
				return ZNet.GetUID();
			}
			return ZNet.instance.GetServerPeer()?.m_uid ?? 0;
		}

		internal static string SendAdd(DateTime local, int minutes, string title, string place)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			long num = ServerTarget();
			if (num == 0L || ZRoutedRpc.instance == null)
			{
				return "Not connected to a server.";
			}
			string text = Cal.Clean(title, 60);
			if (text.Length < 3)
			{
				return "Give the event a name (3 letters or more).";
			}
			DateTime dateTime = DateTime.SpecifyKind(local, DateTimeKind.Local).ToUniversalTime();
			if (dateTime < DateTime.UtcNow.AddHours(-1.0))
			{
				return "That time has already passed.";
			}
			ZPackage val = new ZPackage();
			val.Write((byte)1);
			val.Write(dateTime.Ticks);
			val.Write(Mathf.Clamp(minutes, 0, 1440));
			val.Write(0);
			val.Write(text);
			val.Write(Cal.Clean(place, 40));
			ZRoutedRpc.instance.InvokeRoutedRPC(num, "VFest_CalAdd", new object[1] { val });
			return "Sent to the server: " + text;
		}

		internal static void SendRemove(int id)
		{
			long num = ServerTarget();
			if (num != 0L && ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(num, "VFest_CalDel", new object[1] { id });
			}
		}

		internal static bool CanRemove(CalEvent e)
		{
			if ((Object)(object)ZNet.instance == (Object)null)
			{
				return false;
			}
			if (ZNet.instance.IsServer() || IsLocalAdmin())
			{
				return true;
			}
			if ((Object)(object)Player.m_localPlayer != (Object)null && e.By == Cal.Clean(Player.m_localPlayer.GetPlayerName(), 40))
			{
				return e.Kind == Kind.Player;
			}
			return false;
		}

		internal static bool IsLocalAdmin()
		{
			if (!s_isAdminLooked)
			{
				s_isAdminLooked = true;
				s_isAdmin = typeof(ZNet).GetMethod("LocalPlayerIsAdminOrHost", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			}
			try
			{
				return s_isAdmin != null && (bool)s_isAdmin.Invoke(s_isAdmin.IsStatic ? null : ZNet.instance, null);
			}
			catch
			{
				return false;
			}
		}

		internal static bool Season(out DateTime endUtc, out int number)
		{
			endUtc = DateTime.MinValue;
			number = 0;
			if (SeasonStartUtc == DateTime.MinValue || SeasonLength <= 0)
			{
				return false;
			}
			endUtc = Cal.SeasonEnd(DateTime.UtcNow, SeasonStartUtc, SeasonLength, out number);
			return true;
		}

		internal static bool Festival(out DateTime startUtc, out DateTime endUtc, out string name)
		{
			startUtc = (endUtc = DateTime.MinValue);
			name = "";
			if (FestivalDays <= 0 || !Season(out endUtc, out var number) || number == 0)
			{
				return false;
			}
			startUtc = endUtc.AddDays(-FestivalDays);
			name = "End-of-season Festival";
			DateTime dateTime = startUtc.ToLocalTime().Date;
			while (dateTime < endUtc.ToLocalTime())
			{
				Holiday holiday = HolidayOn(dateTime);
				if (holiday != null)
				{
					name = holiday.Name + " Festival";
					break;
				}
				dateTime = dateTime.AddDays(1.0);
			}
			return true;
		}

		internal static Holiday HolidayOn(DateTime localDay)
		{
			foreach (Holiday holiday in Holidays)
			{
				if (holiday.Contains(localDay.Month, localDay.Day))
				{
					return holiday;
				}
			}
			return null;
		}

		internal static List<CalEvent> On(DateTime localDay)
		{
			List<CalEvent> list = new List<CalEvent>();
			DateTime date = localDay.Date;
			DateTime dateTime = date.AddDays(1.0);
			foreach (CalEvent @event in Events)
			{
				DateTime dateTime2 = @event.Start.ToLocalTime();
				DateTime dateTime3 = @event.End.ToLocalTime();
				if (dateTime2 < dateTime && (dateTime3 > date || dateTime2 >= date))
				{
					list.Add(@event);
				}
			}
			return list;
		}

		internal static string Span(DateTime utc)
		{
			TimeSpan timeSpan = utc - DateTime.UtcNow;
			if (timeSpan.TotalMinutes < 1.0)
			{
				return "now";
			}
			if (timeSpan.TotalHours < 1.0)
			{
				return "in " + (int)timeSpan.TotalMinutes + " min";
			}
			if (timeSpan.TotalHours < 24.0)
			{
				return "in " + (int)timeSpan.TotalHours + " h";
			}
			int num = (int)Math.Ceiling(timeSpan.TotalDays - 0.5);
			return "in " + num + ((num == 1) ? " day" : " days");
		}

		internal static string Local(DateTime utc)
		{
			return utc.ToLocalTime().ToString("ddd MMM d, HH:mm", CultureInfo.InvariantCulture);
		}

		internal static string HudLine()
		{
			List<string> list = new List<string>();
			string text = SeasonsBridge.Describe();
			if (text.Length > 0)
			{
				list.Add(text);
			}
			if (!HaveData)
			{
				return string.Join("  ·  ", list.ToArray());
			}
			DateTime now = DateTime.UtcNow;
			CalEvent calEvent = Events.Find((CalEvent e) => e.End > now);
			DateTime startUtc;
			DateTime endUtc;
			string name;
			bool flag = Festival(out startUtc, out endUtc, out name);
			if (flag && now >= startUtc && now < endUtc)
			{
				list.Add(name + " now");
			}
			else if (calEvent != null && calEvent.Start < now)
			{
				list.Add(calEvent.Title + " now");
			}
			else if (calEvent != null && calEvent.Start < now.AddDays(2.0))
			{
				list.Add(calEvent.Title + " " + Span(calEvent.Start));
			}
			else if (flag && startUtc < now.AddDays(7.0))
			{
				list.Add(name + " " + Span(startUtc));
			}
			else
			{
				Holiday holiday = HolidayOn(DateTime.Now);
				DateTime endUtc2;
				int number;
				if (holiday != null)
				{
					list.Add(holiday.Name);
				}
				else if (Season(out endUtc2, out number) && number > 0)
				{
					list.Add("Season ends " + Span(endUtc2));
				}
			}
			return string.Join("  ·  ", list.ToArray());
		}

		internal static IEnumerable<string> Describe(int days)
		{
			DateTime now = DateTime.UtcNow;
			if (!HaveData)
			{
				yield return "Calendar: nothing received from the server yet.";
				yield break;
			}
			if (Season(out var endUtc, out var number))
			{
				yield return (number == 0) ? ("The season starts " + Local(endUtc) + ".") : ("Season " + number + " ends " + Local(endUtc) + " (" + Span(endUtc) + ").");
			}
			if (Festival(out var startUtc, out var endUtc2, out var name))
			{
				yield return name + ": " + Local(startUtc) + " to " + Local(endUtc2) + ".";
			}
			int shown = 0;
			foreach (CalEvent @event in Events)
			{
				if (!(@event.End <= now) && !(@event.Start > now.AddDays(days)))
				{
					shown++;
					yield return "#" + @event.Id + "  " + Local(@event.Start) + "  " + @event.Title + ((@event.Place.Length > 0) ? (" @ " + @event.Place) : "") + "  (" + @event.By + ")";
				}
			}
			if (shown == 0)
			{
				yield return "No events in the next " + days + " days. Add one: cal add YYYY-MM-DD HH:MM title";
			}
		}
	}
	internal static class SeasonsBridge
	{
		private static bool s_looked;

		private static FieldInfo s_stateField;

		private static MemberInfo s_season;

		private static MemberInfo s_day;

		private static MemberInfo s_daysIn;

		private static float s_next;

		private static string s_cached = "";

		internal static string Describe()
		{
			if (Time.time < s_next)
			{
				return s_cached;
			}
			s_next = Time.time + 5f;
			s_cached = "";
			try
			{
				Look();
				if (s_stateField == null)
				{
					return s_cached;
				}
				object value = s_stateField.GetValue(null);
				if (value == null)
				{
					return s_cached;
				}
				object obj = Get(s_season, value);
				if (obj == null)
				{
					return s_cached;
				}
				string? text = obj.ToString();
				object obj2 = Get(s_day, value);
				object obj3 = Get(s_daysIn, value);
				s_cached = text + ((obj2 is int) ? (" day " + (int)obj2 + ((obj3 is int) ? ("/" + (int)obj3) : "")) : "");
			}
			catch
			{
				s_cached = "";
			}
			return s_cached;
		}

		private static object Get(MemberInfo m, object o)
		{
			if (m is MethodInfo)
			{
				return ((MethodInfo)m).Invoke(((MethodInfo)m).IsStatic ? null : o, null);
			}
			if (m is PropertyInfo)
			{
				return ((PropertyInfo)m).GetValue(((PropertyInfo)m).GetGetMethod(nonPublic: true).IsStatic ? null : o, null);
			}
			if (m is FieldInfo)
			{
				return ((FieldInfo)m).GetValue(((FieldInfo)m).IsStatic ? null : o);
			}
			return null;
		}

		private static void Look()
		{
			if (s_looked)
			{
				return;
			}
			s_looked = true;
			Type type = null;
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (!(assembly.GetName().Name != "Seasons"))
				{
					type = assembly.GetType("Seasons.Seasons");
					if (type != null)
					{
						break;
					}
				}
			}
			if (type == null)
			{
				Plugin.Log.LogInfo((object)"Calendar: Seasons mod not found; world season not shown.");
				return;
			}
			s_stateField = type.GetField("seasonState", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			Type nestedType = type.GetNestedType("Season", BindingFlags.Public | BindingFlags.NonPublic);
			if (s_stateField == null || nestedType == null)
			{
				Plugin.Log.LogWarning((object)"Calendar: Seasons found but seasonState/Season not; world season not shown.");
				s_stateField = null;
				return;
			}
			Type fieldType = s_stateField.FieldType;
			MemberInfo[] members = fieldType.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MemberInfo memberInfo in members)
			{
				Type type2 = Returns(memberInfo);
				if (!(type2 == null))
				{
					string text = memberInfo.Name.ToLowerInvariant();
					if (type2 == nestedType && s_season == null && text.Contains("current") && !text.Contains("next") && !text.Contains("previous"))
					{
						s_season = memberInfo;
					}
					else if (type2 == typeof(int) && s_day == null && text.Contains("current") && text.Contains("day"))
					{
						s_day = memberInfo;
					}
					else if (type2 == typeof(int) && s_daysIn == null && text.Contains("days") && text.Contains("season") && !text.Contains("current"))
					{
						s_daysIn = memberInfo;
					}
				}
			}
			if (s_season == null)
			{
				members = fieldType.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MemberInfo m in members)
				{
					if (Returns(m) == nestedType)
					{
						s_season = m;
						break;
					}
				}
			}
			Plugin.Log.LogInfo((object)("Calendar: Seasons hooked - season " + Name(s_season) + ", day " + Name(s_day) + ", days in season " + Name(s_daysIn) + "."));
			if (s_season == null)
			{
				s_stateField = null;
			}
		}

		private static Type Returns(MemberInfo m)
		{
			if (m is MethodInfo)
			{
				MethodInfo methodInfo = (MethodInfo)m;
				if (methodInfo.GetParameters().Length != 0 || methodInfo.IsSpecialName || methodInfo.ContainsGenericParameters)
				{
					return null;
				}
				return methodInfo.ReturnType;
			}
			if (m is PropertyInfo)
			{
				PropertyInfo propertyInfo = (PropertyInfo)m;
				if (propertyInfo.GetIndexParameters().Length != 0 || !(propertyInfo.GetGetMethod(nonPublic: true) != null))
				{
					return null;
				}
				return propertyInfo.PropertyType;
			}
			if (m is FieldInfo)
			{
				return ((FieldInfo)m).FieldType;
			}
			return null;
		}

		private static string Name(MemberInfo m)
		{
			if (!(m == null))
			{
				return m.MemberType.ToString() + " " + m.Name;
			}
			return "(none)";
		}
	}
	public sealed class Discord
	{
		private sealed class Job
		{
			public string Method;

			public string Url;

			public string Body;

			public Action<bool, int, string> Done;
		}

		private readonly Queue<Job> _jobs = new Queue<Job>();

		private readonly Queue<Action> _results = new Queue<Action>();

		private Thread _thread;

		private volatile bool _stop;

		public bool Enqueue(string method, string url, string body, Action<bool, int, string> done)
		{
			if (string.IsNullOrEmpty(url))
			{
				return false;
			}
			lock (_jobs)
			{
				if (_jobs.Count > 40)
				{
					return false;
				}
				_jobs.Enqueue(new Job
				{
					Method = method,
					Url = url,
					Body = body,
					Done = done
				});
				if (_thread == null)
				{
					_thread = new Thread(Run)
					{
						IsBackground = true,
						Name = "VargheimFestival-discord"
					};
					_thread.Start();
				}
				Monitor.Pulse(_jobs);
			}
			return true;
		}

		public void Pump()
		{
			while (true)
			{
				Action action;
				lock (_results)
				{
					if (_results.Count == 0)
					{
						break;
					}
					action = _results.Dequeue();
				}
				try
				{
					action();
				}
				catch
				{
				}
			}
		}

		public void Stop()
		{
			_stop = true;
			lock (_jobs)
			{
				Monitor.Pulse(_jobs);
			}
		}

		private void Run()
		{
			while (!_stop)
			{
				Job job;
				lock (_jobs)
				{
					while (_jobs.Count == 0 && !_stop)
					{
						Monitor.Wait(_jobs, 5000);
					}
					if (_stop)
					{
						break;
					}
					job = _jobs.Dequeue();
				}
				int status;
				string response;
				bool ok = Request(job.Method, job.Url, job.Body, 15000, out status, out response);
				if (job.Done != null)
				{
					Job j = job;
					lock (_results)
					{
						_results.Enqueue(delegate
						{
							j.Done(ok, status, response);
						});
					}
				}
				Thread.Sleep(600);
			}
		}

		public static bool Request(string method, string url, string body, int timeoutMs, out int status, out string response)
		{
			status = 0;
			response = null;
			try
			{
				try
				{
					ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
				}
				catch
				{
				}
				byte[] bytes = Encoding.UTF8.GetBytes(body ?? string.Empty);
				HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
				httpWebRequest.Method = method;
				httpWebRequest.ContentType = "application/json";
				httpWebRequest.ContentLength = bytes.Length;
				httpWebRequest.Timeout = timeoutMs;
				httpWebRequest.ReadWriteTimeout = timeoutMs;
				httpWebRequest.UserAgent = "VargheimExtras/1.0";
				using (Stream stream = httpWebRequest.GetRequestStream())
				{
					stream.Write(bytes, 0, bytes.Length);
				}
				using HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
				status = (int)httpWebResponse.StatusCode;
				using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8))
				{
					response = streamReader.ReadToEnd();
				}
				return status >= 200 && status < 300;
			}
			catch (WebException ex)
			{
				response = ex.Message;
				try
				{
					if (ex.Response is HttpWebResponse httpWebResponse2)
					{
						status = (int)httpWebResponse2.StatusCode;
						httpWebResponse2.Close();
					}
				}
				catch
				{
				}
				return false;
			}
			catch (Exception ex2)
			{
				response = ex2.Message;
				return false;
			}
		}
	}
	internal static class Gear
	{
		internal const string TableName = "vfest_piece_table";

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

		private static Mesh s_capeMesh;

		internal static PieceTable Table;

		internal static int Registered;

		private static string Assets => Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)Plugin.Instance).Info.Location), "assets");

		internal static void Bind()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			CustomPieceTable val = new CustomPieceTable("vfest_piece_table", new PieceTableConfig
			{
				UseCategories = false,
				CanRemovePieces = true
			});
			PieceManager.Instance.AddPieceTable(val);
			Table = val.PieceTable;
			PrefabManager.OnVanillaPrefabsAvailable += Register;
		}

		private static Texture2D Texture(string path)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			if (s_textures.TryGetValue(path, out var value))
			{
				return value;
			}
			value = new Texture2D(2, 2);
			if (!ImageConversion.LoadImage(value, File.ReadAllBytes(path)))
			{
				throw new InvalidDataException(path);
			}
			((Texture)value).wrapMode = (TextureWrapMode)1;
			s_textures.Add(path, value);
			return value;
		}

		private static Sprite Icon(string key)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = Texture(Path.Combine(Assets, key + "-icon.png"));
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
		}

		private static void Register()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			PrefabManager.OnVanillaPrefabsAvailable -= Register;
			try
			{
				ItemConfig val = new ItemConfig();
				val.Name = "Festival Hammer";
				val.Description = "Raise the tournament grounds.";
				val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2]
				{
					new RequirementConfig("Wood", 3, 0, false),
					new RequirementConfig("Stone", 2, 0, false)
				};
				CustomItem val2 = new CustomItem("vfest_hammer", "Hammer", val);
				SharedData shared = val2.ItemPrefab.GetComponent<ItemDrop>().m_itemData.m_shared;
				shared.m_buildPieces = Table;
				shared.m_icons = (Sprite[])(object)new Sprite[1] { Icon("hammer") };
				shared.m_value = 0;
				ItemManager.Instance.AddItem(val2);
				Registered++;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Festival Hammer: " + ex.Message));
			}
			foreach (string item in Lines("capes.tsv"))
			{
				Try(item, RegisterCape);
			}
			foreach (string item2 in Lines("items.tsv"))
			{
				Try(item2, RegisterItem);
			}
			Plugin.Log.LogInfo((object)("Festival gear: " + Registered + " items registered."));
		}

		private static IEnumerable<string> Lines(string file)
		{
			string text = Path.Combine(Assets, file);
			if (!File.Exists(text))
			{
				Plugin.Log.LogWarning((object)("Festival gear: " + text + " missing."));
				return new string[0];
			}
			return File.ReadAllLines(text);
		}

		private static void Try(string line, Action<string[]> act)
		{
			if (string.IsNullOrEmpty(line.Trim()))
			{
				return;
			}
			string[] array = line.Split('\t');
			try
			{
				act(array);
				Registered++;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Festival gear " + array[0] + ": " + ex.Message));
			}
		}

		private static void RegisterCape(string[] row)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			CustomItem val = new CustomItem(row[0], "CapeLox", new ItemConfig
			{
				Name = row[2],
				Description = "Woven for the Vargheim games."
			});
			SkinnedMeshRenderer componentInChildren = ((Component)val.ItemPrefab.transform.Find("attach_skin")).GetComponentInChildren<SkinnedMeshRenderer>(true);
			if (!Object.op_Implicit((Object)(object)s_capeMesh))
			{
				byte[] array = File.ReadAllBytes(Path.Combine(Assets, "cape.uv"));
				if (array.Length != 8 * componentInChildren.sharedMesh.vertexCount)
				{
					throw new InvalidDataException("Lox cape UV count " + array.Length / 8 + " vs mesh " + componentInChildren.sharedMesh.vertexCount);
				}
				Vector2[] array2 = (Vector2[])(object)new Vector2[array.Length / 8];
				for (int i = 0; i < array2.Length; i++)
				{
					array2[i] = new Vector2(BitConverter.ToSingle(array, i * 8), BitConverter.ToSingle(array, i * 8 + 4));
				}
				s_capeMesh = Object.Instantiate<Mesh>(componentInChildren.sharedMesh);
				s_capeMesh.uv = array2;
			}
			componentInChildren.sharedMesh = s_capeMesh;
			Material val2 = new Material(((Renderer)componentInChildren).sharedMaterial);
			val2.mainTexture = (Texture)(object)Texture(Path.Combine(Assets, row[1] + ".png"));
			val2.mainTextureScale = Vector2.one;
			val2.mainTextureOffset = Vector2.zero;
			((Renderer)componentInChildren).sharedMaterial = val2;
			SharedData shared = val.ItemPrefab.GetComponent<ItemDrop>().m_itemData.m_shared;
			shared.m_variants = 1;
			shared.m_icons = (Sprite[])(object)new Sprite[1] { Icon(row[1]) };
			SharedData shared2 = PrefabManager.Instance.GetPrefab("CapeLinen").GetComponent<ItemDrop>().m_itemData.m_shared;
			shared.m_damageModifiers = new List<DamageModPair>(shared2.m_damageModifiers);
			shared.m_armor = shared2.m_armor;
			shared.m_armorPerLevel = shared2.m_armorPerLevel;
			shared.m_weight = shared2.m_weight;
			shared.m_equipStatusEffect = shared2.m_equipStatusEffect;
			shared.m_value = 0;
			ItemManager.Instance.AddItem(val);
		}

		private static void RegisterItem(string[] row)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: 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_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Expected O, but got Unknown
			CustomItem val = new CustomItem(row[0], row[1], new ItemConfig
			{
				Name = row[2],
				Description = "Tournament equipment."
			});
			GameObject itemPrefab = val.ItemPrefab;
			SharedData shared = itemPrefab.GetComponent<ItemDrop>().m_itemData.m_shared;
			shared.m_icons = (Sprite[])(object)new Sprite[1] { Icon(row[3]) };
			shared.m_value = 0;
			if (row[0].StartsWith("vfest_lifting_stone_", StringComparison.Ordinal))
			{
				int.TryParse(row[0].Substring(row[0].Length - 1), out var result);
				shared.m_maxStackSize = 1;
				shared.m_weight = 40f * (float)Mathf.Clamp(result, 1, 4);
				shared.m_teleportable = false;
			}
			string text = Path.Combine(Assets, Path.Combine("items", row[0]));
			if (Directory.Exists(text))
			{
				Transform val2 = itemPrefab.transform.Find("attach") ?? itemPrefab.transform.Find("model");
				if ((Object)(object)val2 != (Object)null)
				{
					MeshRenderer[] componentsInChildren = ((Component)val2).GetComponentsInChildren<MeshRenderer>(true);
					if (componentsInChildren.Length != 0)
					{
						Material sharedMaterial = ((Renderer)componentsInChildren[0]).sharedMaterial;
						MeshRenderer[] array = componentsInChildren;
						for (int i = 0; i < array.Length; i++)
						{
							((Renderer)array[i]).enabled = false;
						}
						string[] files = Directory.GetFiles(text, "*.obj");
						foreach (string path in files)
						{
							string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
							Obj.Result result2 = Obj.Load(path, row[0] + fileNameWithoutExtension);
							if (result2 != null)
							{
								GameObject val3 = new GameObject(fileNameWithoutExtension);
								val3.transform.SetParent(val2, false);
								val3.layer = ((Component)val2).gameObject.layer;
								val3.AddComponent<MeshFilter>().sharedMesh = result2.Mesh;
								Material val4 = new Material(sharedMaterial);
								val4.mainTexture = (Texture)(object)Texture(Path.Combine(text, fileNameWithoutExtension + ".png"));
								((Renderer)val3.AddComponent<MeshRenderer>()).sharedMaterial = val4;
							}
						}
					}
				}
			}
			ItemManager.Instance.AddItem(val);
		}
	}
	internal static class Obj
	{
		internal sealed class Result
		{
			internal Mesh Mesh;

			internal int Triangles;

			internal int Reordered;
		}

		internal static Vector3 Pos(float x, float y, float z)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(x, z, y);
		}

		internal static Result Load(string path, string meshName)
		{
			//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d8: Expected O, but got Unknown
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: 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_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_0258: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: 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_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0314: Unknown result type (might be due to invalid IL or missing references)
			//IL_0319: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Unknown result type (might be due to invalid IL or missing references)
			//IL_0362: Unknown result type (might be due to invalid IL or missing references)
			//IL_0358: Unknown result type (might be due to invalid IL or missing references)
			//IL_0383: Unknown result type (might be due to invalid IL or missing references)
			//IL_0376: Unknown result type (might be due to invalid IL or missing references)
			List<Vector3> list = new List<Vector3>();
			List<Vector3> list2 = new List<Vector3>();
			List<Vector2> list3 = new List<Vector2>();
			List<Vector3> list4 = new List<Vector3>();
			List<Vector3> list5 = new List<Vector3>();
			List<Vector2> list6 = new List<Vector2>();
			List<int> list7 = new List<int>();
			int num = 0;
			int num2 = 0;
			char[] separator = new char[2] { ' ', '\t' };
			int[] array = new int[4];
			int[] array2 = new int[4];
			int[] array3 = new int[4];
			int[] array4 = new int[3];
			foreach (string item in File.ReadLines(path))
			{
				string text = item.Trim();
				if (text.Length < 2 || text[0] == '#')
				{
					continue;
				}
				string[] array5 = text.Split(separator, StringSplitOptions.RemoveEmptyEntries);
				if (array5[0] == "v" && array5.Length >= 4)
				{
					list.Add(Pos(F(array5[1]), F(array5[2]), F(array5[3])));
				}
				else if (array5[0] == "vn" && array5.Length >= 4)
				{
					Vector3 val = Pos(F(array5[1]), F(array5[2]), F(array5[3]));
					list2.Add(((Vector3)(ref val)).normalized);
				}
				else if (array5[0] == "vt" && array5.Length >= 3)
				{
					list3.Add(new Vector2(F(array5[1]), F(array5[2])));
				}
				else
				{
					if (!(array5[0] == "f") || array5.Length < 4)
					{
						continue;
					}
					int num3 = array5.Length - 1;
					if (array.Length < num3)
					{
						array = new int[num3];
						array2 = new int[num3];
						array3 = new int[num3];
					}
					for (int i = 0; i < num3; i++)
					{
						string token = array5[i + 1];
						int start = 0;
						array[i] = ReadIndex(token, ref start, list.Count);
						array2[i] = ReadOptionalIndex(token, ref start, list3.Count);
						array3[i] = ReadOptionalIndex(token, ref start, list2.Count);
					}
					for (int j = 1; j + 1 < num3; j++)
					{
						array4[0] = 0;
						array4[1] = j;
						array4[2] = j + 1;
						Vector3 val2 = list[array[array4[0]]];
						Vector3 val3 = list[array[array4[1]]];
						Vector3 val4 = list[array[array4[2]]];
						Vector3 val5 = Vector3.Cross(val3 - val2, val4 - val2);
						if (((Vector3)(ref val5)).sqrMagnitude < 1E-14f)
						{
							continue;
						}
						Vector3 val6 = Vector3.zero;
						int[] array6 = array4;
						foreach (int num4 in array6)
						{
							if (array3[num4] >= 0)
							{
								val6 += list2[array3[num4]];
							}
						}
						if (((Vector3)(ref val6)).sqrMagnitude < 1E-10f)
						{
							val6 = -val5;
						}
						bool num5 = Vector3.Dot(val5, val6) < 0f;
						if (num5)
						{
							array4[1] = j + 1;
							array4[2] = j;
							num++;
						}
						num2++;
						Vector3 val7 = (num5 ? (-((Vector3)(ref val5)).normalized) : ((Vector3)(ref val5)).normalized);
						array6 = array4;
						foreach (int num6 in array6)
						{
							list7.Add(list4.Count);
							list4.Add(list[array[num6]]);
							list5.Add((array3[num6] >= 0) ? list2[array3[num6]] : val7);
							list6.Add((array2[num6] >= 0) ? list3[array2[num6]] : Vector2.zero);
						}
					}
				}
			}
			if (list7.Count == 0)
			{
				return null;
			}
			Mesh val8 = new Mesh();
			((Object)val8).name = meshName;
			if (list4.Count > 65000)
			{
				val8.indexFormat = (IndexFormat)1;
			}
			val8.SetVertices(list4);
			val8.SetNormals(list5);
			val8.SetUVs(0, list6);
			val8.SetTriangles(list7, 0);
			val8.RecalculateBounds();
			val8.RecalculateTangents();
			return new Result
			{
				Mesh = val8,
				Triangles = num2,
				Reordered = num
			};
		}

		private static float F(string s)
		{
			return float.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture);
		}

		private static int ReadOptionalIndex(string token, ref int start, int count)
		{
			if (start >= token.Length)
			{
				return -1;
			}
			if (token[start] == '/')
			{
				start++;
				return -1;
			}
			return ReadIndex(token, ref start, count);
		}

		private static int ReadIndex(string token, ref int start, int count)
		{
			int num = token.IndexOf('/', start);
			if (num < 0)
			{
				num = token.Length;
			}
			int num2 = 0;
			bool flag = num > start;
			int num3 = start;
			while (flag && num3 < num)
			{
				int num4 = token[num3] - 48;
				if (num4 < 0 || num4 > 9 || num2 > (int.MaxValue - num4) / 10)
				{
					flag = false;
				}
				else
				{
					num2 = num2 * 10 + num4;
				}
				num3++;
			}
			if (!flag)
			{
				num2 = int.Parse(token.Substring(start, num - start), CultureInfo.InvariantCulture);
			}
			start = num + 1;
			int num5 = ((num2 > 0) ? (num2 - 1) : (count + num2));
			if (num5 < 0 || num5 >= count)
			{
				throw new FormatException("index " + num2 + " out of range");
			}
			return num5;
		}
	}
	[BepInDependency("com.jotunn.jotunn", "2.30.2")]
	[BepInDependency("digi.vargheim.roundhouse", "0.5.21")]
	[BepInIncompatibility("digi.vargheim.tourney")]
	[BepInIncompatibility("digi.vargheim.festivalcapefit")]
	[BepInPlugin("digi.vargheim.festival", "VargheimFestival", "0.2.6")]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch]
		internal static class Patches
		{
			private static bool s_commands;

			[HarmonyPatch(typeof(Menu), "IsVisible")]
			[HarmonyPostfix]
			private static void MenuVisible(ref bool __result)
			{
				if (Ui.Open)
				{
					__result = true;
				}
			}

			[HarmonyPatch(typeof(GameCamera), "UpdateMouseCapture")]
			[HarmonyPrefix]
			private static bool MouseCapture()
			{
				if (!Ui.Open)
				{
					return true;
				}
				Cursor.lockState = (CursorLockMode)0;
				Cursor.visible = true;
				return false;
			}

			[HarmonyPatch(typeof(Terminal), "InitTerminal")]
			[HarmonyPostfix]
			private static void Commands()
			{
				if (!s_commands)
				{
					s_commands = true;
					RegisterCommands();
				}
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static Action<long, ZPackage> <0>__OnAdd;

			public static Action<long, int> <1>__OnRemove;

			public static Action<long, ZPackage> <2>__OnList;

			public static ConsoleEvent <3>__Command;
		}

		public const string Guid = "digi.vargheim.festival";

		public const string PluginName = "VargheimFestival";

		public const string Version = "0.2.6";

		internal const string RpcList = "VFest_CalList";

		internal const string RpcRequest = "VFest_CalReq";

		internal const string RpcAdd = "VFest_CalAdd";

		internal const string RpcRemove = "VFest_CalDel";

		internal const byte PacketVersion = 1;

		internal static Plugin Instance;

		internal static ManualLogSource Log;

		internal static ConfigEntry<string> Holidays;

		internal static ConfigEntry<string> SeasonStart;

		internal static ConfigEntry<string> WebhookUrl;

		internal static ConfigEntry<string> DigestDay;

		internal static ConfigEntry<int> SeasonLengthDays;

		internal static ConfigEntry<int> FestivalDays;

		internal static ConfigEntry<int> MaxPerPlayer;

		internal static ConfigEntry<int> MaxDaysAhead;

		internal static ConfigEntry<int> DigestHourUtc;

		internal static ConfigEntry<int> KeepDays;

		internal static ConfigEntry<bool> PostNewEvents;

		internal static ConfigEntry<KeyboardShortcut> PanelKey;

		internal static ConfigEntry<bool> ShowHudLine;

		internal static ConfigEntry<int> HudOffsetY;

		private Harmony _harmony;

		private static ZRoutedRpc s_registeredOn;

		private void Awake()
		{
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			Holidays = ((BaseUnityPlugin)this).Config.Bind<string>("Server", "Holidays", "12-21..12-28 Yule; 12-31..01-01 New Year; 01-23..01-25 Thorrablot; 03-20..03-22 Spring Games; 06-20..06-22 Midsummer; 10-14..10-16 Winter Nights", "Server: yearly holidays shown on everyone's calendar. MM-DD..MM-DD Name, separated by ';'. A single day may be written MM-DD Name.");
			SeasonStart = ((BaseUnityPlugin)this).Config.Bind<string>("Server", "SeasonStart", "2026-11-23", "Server: first day of the current server season, YYYY-MM-DD (UTC midnight). Empty = no season shown. Default 2026-11-23 is Digi's test date (Nov 22); the real start is still to be decided.");
			SeasonLengthDays = ((BaseUnityPlugin)this).Config.Bind<int>("Server", "SeasonLengthDays", 21, "Server: length of a server season in real days (Digi: about 3 weeks). Seasons follow each other back to back.");
			FestivalDays = ((BaseUnityPlugin)this).Config.Bind<int>("Server", "FestivalDays", 3, "Server: the festival takes the last N days of every season (0 = none shown).");
			MaxPerPlayer = ((BaseUnityPlugin)this).Config.Bind<int>("Server", "MaxEventsPerPlayer", 3, "Server: upcoming events one player may have at once (admins unlimited).");
			MaxDaysAhead = ((BaseUnityPlugin)this).Config.Bind<int>("Server", "MaxDaysAhead", 90, "Server: how far ahead an event may be posted.");
			KeepDays = ((BaseUnityPlugin)this).Config.Bind<int>("Server", "KeepEndedDays", 7, "Server: ended events are removed after this many days.");
			WebhookUrl = ((BaseUnityPlugin)this).Config.Bind<string>("Discord", "WebhookUrl", "", "Server: Discord webhook for the calendar (Digi, Nov 22: the raven post channel). Empty = no Discord posts. Keep this file private.");
			PostNewEvents = ((BaseUnityPlugin)this).Config.Bind<bool>("Discord", "PostNewEvents", true, "Server: post each new event to the webhook.");
			DigestDay = ((BaseUnityPlugin)this).Config.Bind<string>("Discord", "DigestDay", "Sunday", "Server: day of the week for the 'coming week' post (UTC). Empty = no digest.");
			DigestHourUtc = ((BaseUnityPlugin)this).Config.Bind<int>("Discord", "DigestHourUtc", 23, "Server: hour (UTC) of the weekly post. 23 UTC = 6 PM Eastern in winter.");
			PanelKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Client", "PanelKey", new KeyboardShortcut((KeyCode)288, Array.Empty<KeyCode>()), "Opens and closes the calendar.");
			ShowHudLine = ((BaseUnityPlugin)this).Config.Bind<bool>("Client", "ShowHudLine", true, "Show the one-line calendar under the minimap (season, next holiday or event).");
			HudOffsetY = ((BaseUnityPlugin)this).Config.Bind<int>("Client", "HudLineGap", 6, "Pixels below the map panel (VargheimHUD) for the calendar line; without VargheimHUD it sits 30 px further below the map.");
			try
			{
				Gear.Bind();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("VargheimFestival: festival gear off: " + ex));
			}
			_harmony = new Harmony("digi.vargheim.festival");
			int num = SafePatch.Apply(_harmony, typeof(Patches), delegate(string s)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)s);
			}, "Festival");
			if (num > 0)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("VargheimFestival: " + num + " patch(es) off - the calendar may not block game input while open."));
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"VargheimFestival 0.2.6 loaded (calendar, festival gear).");
		}

		private void OnDestroy()
		{
			Server.Shutdown();
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
			}
		}

		private void Update()
		{
			ZNet instance = ZNet.instance;
			if (ZRoutedRpc.instance != null && s_registeredOn != ZRoutedRpc.instance && (Object)(object)instance != (Object)null)
			{
				s_registeredOn = ZRoutedRpc.instance;
				if (instance.IsServer())
				{
					Server.Start(Paths.ConfigPath);
					ZRoutedRpc.instance.Register("VFest_CalReq", (Action<long>)Server.OnRequest);
					ZRoutedRpc.instance.Register<ZPackage>("VFest_CalAdd", (Action<long, ZPackage>)Server.OnAdd);
					ZRoutedRpc.instance.Register<int>("VFest_CalDel", (Action<long, int>)Server.OnRemove);
				}
				ZRoutedRpc.instance.Register<ZPackage>("VFest_CalList", (Action<long, ZPackage>)Client.OnList);
				Client.Reset();
			}
			if ((Object)(object)instance != (Object)null && instance.IsServer())
			{
				Server.Tick();
			}
			Client.Tick();
			Ui.Tick();
		}

		private void OnGUI()
		{
			Ui.Draw();
		}

		internal static void RegisterCommands()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: 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_005a: Expected O, but got Unknown
			object obj = <>O.<3>__Command;
			if (obj == null)
			{
				ConsoleEvent val = Command;
				<>O.<3>__Command = val;
				obj = (object)val;
			}
			new ConsoleCommand("cal", "[add YYYY-MM-DD HH:MM title | del id | list] - the server calendar (no argument opens it)", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			object obj2 = <>O.<3>__Command;
			if (obj2 == null)
			{
				ConsoleEvent val2 = Command;
				<>O.<3>__Command = val2;
				obj2 = (object)val2;
			}
			new ConsoleCommand("calendar", "same as /cal", (ConsoleEvent)obj2, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}

		private static void Command(ConsoleEventArgs args)
		{
			Terminal context = args.Context;
			string[] args2 = args.Args;
			if (args2.Length < 2)
			{
				Ui.Toggle();
				return;
			}
			switch (args2[1].ToLowerInvariant())
			{
			case "list":
			{
				foreach (string item in Client.Describe(14))
				{
					context.AddString(item);
				}
				break;
			}
			case "del":
			case "remove":
			{
				if (args2.Length < 3 || !int.TryParse(args2[2], out var result))
				{
					context.AddString("cal del <id>  (ids are shown by cal list)");
				}
				else
				{
					Client.SendRemove(result);
				}
				break;
			}
			case "add":
			{
				if (args2.Length < 5 || !Cal.TryParseLocal(args2[2], args2[3], out var local))
				{
					context.AddString("cal add 2026-12-20 20:00 Raid night at the Split-Fang hall");
					break;
				}
				string title = string.Join(" ", args2, 4, args2.Length - 4);
				context.AddString(Client.SendAdd(local, 60, title, ""));
				break;
			}
			default:
				context.AddString("cal | cal list | cal add YYYY-MM-DD HH:MM title | cal del id");
				break;
			}
		}
	}
	public static class SafePatch
	{
		public delegate void Logger(string message);

		public static int Apply(Harmony harmony, Type patchClass, Logger warn, string name = null)
		{
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			name = name ?? patchClass.Name;
			int num = 0;
			MethodInfo[] methods = patchClass.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod((MethodBase)methodInfo);
				if (fromMethod == null || fromMethod.Count == 0)
				{
					continue;
				}
				HarmonyMethod val = HarmonyMethod.Merge(fromMethod);
				bool flag = ((MemberInfo)methodInfo).GetCustomAttribute<HarmonyPrefix>() != null;
				bool flag2 = ((MemberInfo)methodInfo).GetCustomAttribute<HarmonyPostfix>() != null;
				bool flag3 = ((MemberInfo)methodInfo).GetCustomAttribute<HarmonyFinalizer>() != null;
				if (!flag && !flag2 && !flag3)
				{
					continue;
				}
				string text = ((val.declaringType != null) ? val.declaringType.Name : "?") + "." + (val.methodName ?? "?");
				try
				{
					MethodBase methodBase = Resolve(val);
					if (methodBase == null)
					{
						num++;
						warn(name + ": " + text + " not found (game update?) - " + methodInfo.Name + " is OFF.");
						continue;
					}
					PatchProcessor val2 = harmony.CreateProcessor(methodBase);
					HarmonyMethod val3 = new HarmonyMethod(methodInfo)
					{
						priority = val.priority,
						before = val.before,
						after = val.after
					};
					if (flag)
					{
						val2.AddPrefix(val3);
					}
					if (flag2)
					{
						val2.AddPostfix(val3);
					}
					if (flag3)
					{
						val2.AddFinalizer(val3);
					}
					val2.Patch();
				}
				catch (Exception ex)
				{
					num++;
					warn(name + ": " + text + " could not be patched (" + ex.GetType().Name + ": " + ex.Message + ") - " + methodInfo.Name + " is OFF.");
				}
			}
			return num;
		}

		public static FieldRef<T, F> FieldRef<T, F>(string field, Logger warn)
		{
			try
			{
				return AccessTools.FieldRefAccess<T, F>(field);
			}
			catch (Exception ex)
			{
				warn?.Invoke(typeof(T).Name + "." + field + " not found (game update?): " + ex.Message);
				return null;
			}
		}

		public static FieldRef<F> StaticFieldRef<F>(Type type, string field, Logger warn)
		{
			try
			{
				FieldInfo fieldInfo = AccessTools.Field(type, field);
				if (fieldInfo == null)
				{
					warn?.Invoke(type.Name + "." + field + " not found (game update?).");
					return null;
				}
				return AccessTools.StaticFieldRefAccess<F>(fieldInfo);
			}
			catch (Exception ex)
			{
				warn?.Invoke(type.Name + "." + field + ": " + ex.Message);
				return null;
			}
		}

		private static MethodBase Resolve(HarmonyMethod info)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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_0034: Expected I4, but got Unknown
			if (info.declaringType == null)
			{
				return null;
			}
			MethodType valueOrDefault = info.methodType.GetValueOrDefault();
			switch (valueOrDefault - 1)
			{
			case 2:
				return AccessTools.Constructor(info.declaringType, info.argumentTypes, false);
			case 3:
				return AccessTools.Constructor(info.declaringType, (Type[])null, true);
			case 0:
				if (info.methodName != null)
				{
					return AccessTools.PropertyGetter(info.declaringType, info.methodName);
				}
				return null;
			case 1:
				if (info.methodName != null)
				{
					return AccessTools.PropertySetter(info.declaringType, info.methodName);
				}
				return null;
			default:
				if (info.methodName == null)
				{
					return null;
				}
				if (info.argumentTypes != null)
				{
					return AccessTools.Method(info.declaringType, info.methodName, info.argumentTypes, (Type[])null);
				}
				try
				{
					return AccessTools.Method(info.declaringType, info.methodName, (Type[])null, (Type[])null);
				}
				catch (AmbiguousMatchException)
				{
					return null;
				}
			}
		}
	}
	internal static class Server
	{
		private static string s_path;

		private static string s_digestPath;

		private static readonly List<CalEvent> s_events = new List<CalEvent>();

		private static int s_nextId = 1;

		private static bool s_started;

		private static float s_nextTick;

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

		private static readonly Discord s_discord = new Discord();

		private static string s_lastDigest = "";

		private static string s_lastConfigKey = "";

		internal static void Start(string configDir)
		{
			s_path = Path.Combine(configDir, "vargheim-calendar.tsv");
			s_digestPath = Path.Combine(configDir, "vargheim-calendar-digest.txt");
			if (s_started)
			{
				return;
			}
			s_started = true;
			s_events.Clear();
			try
			{
				if (File.Exists(s_path))
				{
					List<string> list = new List<string>();
					s_events.AddRange(Cal.FromTsv(File.ReadAllText(s_path, Encoding.UTF8), list));
					foreach (string item in list)
					{
						Plugin.Log.LogWarning((object)("Calendar file: " + item));
					}
				}
				if (File.Exists(s_digestPath))
				{
					s_lastDigest = File.ReadAllText(s_digestPath).Trim();
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Calendar: could not read " + s_path + ": " + ex.Message));
			}
			foreach (CalEvent s_event in s_events)
			{
				s_nextId = Math.Max(s_nextId, s_event.Id + 1);
			}
			Prune();
			List<string> list2 = new List<string>();
			Cal.ParseHolidays(Plugin.Holidays.Value, list2);
			foreach (string item2 in list2)
			{
				Plugin.Log.LogWarning((object)("Calendar holidays: " + item2));
			}
			Plugin.Log.LogInfo((object)("Calendar (server): " + s_events.Count + " event(s) loaded, " + Cal.ParseHolidays(Plugin.Holidays.Value, null).Count + " holiday(s), season start '" + Plugin.SeasonStart.Value + "' x " + Plugin.SeasonLengthDays.Value + " days" + (string.IsNullOrEmpty(Plugin.WebhookUrl.Value) ? ", Discord off." : ", Discord on.")));
			s_lastConfigKey = ConfigKey();
		}

		internal static void Shutdown()
		{
			s_discord.Stop();
		}

		internal static void Tick()
		{
			if (!s_started)
			{
				return;
			}
			s_discord.Pump();
			if (!(Time.time < s_nextTick))
			{
				s_nextTick = Time.time + 30f;
				if (Prune())
				{
					Save();
					Broadcast();
				}
				string text = ConfigKey();
				if (text != s_lastConfigKey)
				{
					s_lastConfigKey = text;
					Broadcast();
				}
				Digest();
			}
		}

		private static string ConfigKey()
		{
			return Plugin.Holidays.Value + "|" + Plugin.SeasonStart.Value + "|" + Plugin.SeasonLengthDays.Value + "|" + Plugin.FestivalDays.Value;
		}

		private static bool Prune()
		{
			long cut = DateTime.UtcNow.AddDays(-Math.Max(0, Plugin.KeepDays.Value)).Ticks;
			return s_events.RemoveAll((CalEvent e) => e.End.Ticks < cut) > 0;
		}

		private static void Save()
		{
			try
			{
				string text = s_path + ".tmp";
				File.WriteAllText(text, Cal.ToTsv(s_events), Encoding.UTF8);
				if (File.Exists(s_path))
				{
					File.Delete(s_path);
				}
				File.Move(text, s_path);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Calendar: could not save " + s_path + ": " + ex.Message));
			}
		}

		internal static ZPackage Package()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write((byte)1);
			val.Write(Plugin.Holidays.Value ?? "");
			val.Write(TryDay(Plugin.SeasonStart.Value, out var utc) ? utc.Ticks : 0);
			val.Write(Plugin.SeasonLengthDays.Value);
			val.Write(Plugin.FestivalDays.Value);
			val.Write(Plugin.MaxPerPlayer.Value);
			val.Write(s_events.Count);
			foreach (CalEvent s_event in s_events)
			{
				val.Write(s_event.Id);
				val.Write(s_event.StartUtc);
				val.Write(s_event.Minutes);
				val.Write((int)s_event.Kind);
				val.Write(s_event.Title);
				val.Write(s_event.Place);
				val.Write(s_event.By);
				val.Write(s_event.ByHost);
			}
			return val;
		}

		internal static bool TryDay(string s, out DateTime utc)
		{
			return DateTime.TryParseExact((s ?? "").Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out utc);
		}

		private static void Broadcast()
		{
			if (ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "VFest_CalList", new object[1] { Package() });
			}
		}

		internal static void OnRequest(long sender)
		{
			if (ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(sender, "VFest_CalList", new object[1] { Package() });
			}
		}

		private static bool Who(long sender, out string name, out string host, out bool admin)
		{
			name = (host = "");
			admin = false;
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			if (sender == ZNet.GetUID())
			{
				name = (((Object)(object)Player.m_localPlayer != (Object)null) ? Player.m_localPlayer.GetPlayerName() : "Host");
				host = "local";
				admin = true;
				return true;
			}
			ZNetPeer peer = instance.GetPeer(sender);
			if (peer == null)
			{
				return false;
			}
			name = peer.m_playerName ?? "";
			try
			{
				host = ((peer.m_socket != null) ? (peer.m_socket.GetHostName() ?? "") : "");
			}
			catch
			{
				host = "";
			}
			admin = IsAdmin(host);
			return host.Length > 0;
		}

		internal static bool IsAdmin(string host)
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null || string.IsNullOrEmpty(host))
			{
				return false;
			}
			try
			{
				FieldInfo fieldInfo = AccessTools.Field(typeof(ZNet), "m_adminList");
				object obj = ((fieldInfo != null) ? fieldInfo.GetValue(instance) : null);
				if (obj == null)
				{
					return false;
				}
				MethodInfo methodInfo = AccessTools.Method(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					return (bool)methodInfo.Invoke(instance, new object[2] { obj, host });
				}
				MethodInfo method = obj.GetType().GetMethod("Contains", new Type[1] { typeof(string) });
				return method != null && (bool)method.Invoke(obj, new object[1] { host });
			}
			catch
			{
				return false;
			}
		}

		private static void Tell(long target, string text)
		{
			if (ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(target, "ShowMessage", new object[2]
				{
					2,
					(text ?? "").Replace('$', ' ')
				});
			}
		}

		internal static void OnAdd(long sender, ZPackage pkg)
		{
			if (!Who(sender, out var name, out var host, out var admin))
			{
				return;
			}
			long num2;
			int num4;
			string s;
			string s2;
			int num3;
			try
			{
				byte num = pkg.ReadByte();
				num2 = pkg.ReadLong();
				num3 = pkg.ReadInt();
				num4 = pkg.ReadInt();
				s = pkg.ReadString();
				s2 = pkg.ReadString();
				if (num == 0)
				{
					return;
				}
			}
			catch
			{
				Tell(sender, "Calendar: your game has a different VargheimFestival version.");
				return;
			}
			s = Cal.Clean(s, 60);
			s2 = Cal.Clean(s2, 40);
			DateTime now = DateTime.UtcNow;
			if (s.Length < 3)
			{
				Tell(sender, "Calendar: give the event a name (3 letters or more).");
				return;
			}
			if (num2 < now.AddHours(-1.0).Ticks || num2 > now.AddDays(Math.Max(1, Plugin.MaxDaysAhead.Value)).Ticks)
			{
				Tell(sender, "Calendar: pick a time between now and " + Plugin.MaxDaysAhead.Value + " days ahead.");
				return;
			}
			num3 = Mathf.Clamp(num3, 0, 1440);
			Kind kind = (admin ? ((Kind)Mathf.Clamp(num4, 0, 2)) : Kind.Player);
			if (!admin)
			{
				if (s_lastAdd.TryGetValue(host, out var value) && Time.time - value < 30f)
				{
					Tell(sender, "Calendar: wait a moment before adding another event.");
					return;
				}
				int count = s_events.FindAll((CalEvent e) => e.ByHost == host && e.End > now).Count;
				if (count >= Math.Max(0, Plugin.MaxPerPlayer.Value))
				{
					Tell(sender, "Calendar: you already have " + count + " upcoming events (the limit is " + Plugin.MaxPerPlayer.Value + "). Remove one first.");
					return;
				}
			}
			s_lastAdd[host] = Time.time;
			CalEvent calEvent = new CalEvent
			{
				Id = s_nextId++,
				StartUtc = num2,
				Minutes = num3,
				Kind = kind,
				Title = s,
				Place = s2,
				By = Cal.Clean(name, 40),
				ByHost = host
			};
			s_events.Add(calEvent);
			s_events.Sort((CalEvent a, CalEvent b) => a.StartUtc.CompareTo(b.StartUtc));
			Save();
			Broadcast();
			Tell(sender, "Added to the calendar: " + s);
			Plugin.Log.LogInfo((object)("Calendar: #" + calEvent.Id + " '" + s + "' at " + calEvent.Start.ToString("yyyy-MM-dd HH:mm") + " UTC by " + calEvent.By + " (" + host + ")"));
			if (Plugin.PostNewEvents.Value)
			{
				Post("\ud83d\udcc5 New on the calendar: **" + Md(s) + "**", When(calEvent) + ((s2.Length > 0) ? ("\n\ud83d\udccd " + Md(s2)) : "") + "\nPosted by " + Md(calEvent.By) + ".");
			}
		}

		internal static void OnRemove(long sender, int id)
		{
			if (Who(sender, out var name, out var host, out var admin))
			{
				CalEvent calEvent = s_events.Find((CalEvent e) => e.Id == id);
				if (calEvent == null)
				{
					Tell(sender, "Calendar: no event #" + id + ".");
					return;
				}
				if (!admin && calEvent.ByHost != host)
				{
					Tell(sender, "Calendar: only the person who posted it (or an admin) can remove it.");
					return;
				}
				s_events.Remove(calEvent);
				Save();
				Broadcast();
				Tell(sender, "Removed from the calendar: " + calEvent.Title);
				Plugin.Log.LogInfo((object)("Calendar: #" + id + " '" + calEvent.Title + "' removed by " + name + " (" + host + (admin ? ", admin" : "") + ")"));
			}
		}

		private static string When(CalEvent e)
		{
			long num = (long)(e.Start - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
			return "\ud83d\udd52 <t:" + num + ":F> (<t:" + num + ":R>)" + ((e.Minutes > 0) ? (", " + ((e.Minutes >= 60) ? (e.Minutes / 60 + " h" + ((e.Minutes % 60 > 0) ? (" " + e.Minutes % 60 + " min") : "")) : (e.Minutes + " min"))) : "");
		}

		private static string Md(string s)
		{
			return (s ?? "").Replace("*", "\\*").Replace("_", "\\_").Replace("`", "'")
				.Replace("@", "@\u200b");
		}

		private static void Post(string title, string body)
		{
			string value = Plugin.WebhookUrl.Value;
			if (!string.IsNullOrEmpty(value))
			{
				string body2 = "{\"allowed_mentions\":{\"parse\":[]},\"embeds\":[{\"title\":" + Json(title) + ",\"description\":" + Json(body) + ",\"color\":15105570}]}";
				if (!s_discord.Enqueue("POST", value, body2, delegate(bool ok, int status, string resp)
				{
					if (!ok)
					{
						Plugin.Log.LogWarning((object)("Calendar: Discord post failed (" + status + ")."));
					}
				}))
				{
					Plugin.Log.LogWarning((object)"Calendar: Discord queue full, post dropped.");
				}
			}
		}

		private static string Json(string s)
		{
			StringBuilder stringBuilder = new StringBuilder("\"");
			string text = s ?? "";
			foreach (char c in text)
			{
				if (c == '"' || c == '\\')
				{
					stringBuilder.Append('\\').Append(c);
				}
				else if (c == '\n')
				{
					stringBuilder.Append("\\n");
				}
				else if (c < ' ')
				{
					stringBuilder.Append(' ');
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.Append('"').ToString();
		}

		private static void Digest()
		{
			if (string.IsNullOrEmpty(Plugin.WebhookUrl.Value) || string.IsNullOrEmpty(Plugin.DigestDay.Value))
			{
				return;
			}
			DayOfWeek dayOfWeek;
			try
			{
				dayOfWeek = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), Plugin.DigestDay.Value.Trim(), ignoreCase: true);
			}
			catch
			{
				return;
			}
			DateTime utcNow = DateTime.UtcNow;
			if (utcNow.DayOfWeek != dayOfWeek || utcNow.Hour < Mathf.Clamp(Plugin.DigestHourUtc.Value, 0, 23))
			{
				return;
			}
			string text = utcNow.ToString("yyyy-MM-dd");
			if (text == s_lastDigest)
			{
				return;
			}
			s_lastDigest = text;
			try
			{
				File.WriteAllText(s_digestPath, text);
			}
			catch
			{
			}
			StringBuilder stringBuilder = new StringBuilder();
			DateTime dateTime = utcNow.AddDays(7.0);
			foreach (CalEvent s_event in s_events)
			{
				if (s_event.End > utcNow && s_event.Start < dateTime)
				{
					stringBuilder.Append("• **").Append(Md(s_event.Title)).Append("** ")
						.Append(When(s_event))
						.Append((s_event.Place.Length > 0) ? (" · " + Md(s_event.Place)) : "")
						.Append('\n');
				}
			}
			foreach (Holiday item in Cal.ParseHolidays(Plugin.Holidays.Value, null))
			{
				DateTime dateTime2 = item.NextStart(utcNow.Date);
				if (dateTime2 < dateTime)
				{
					stringBuilder.Append("• \ud83c\udf89 ").Append(Md(item.Name)).Append(" from ")
						.Append(dateTime2.ToString("ddd MMM d", CultureInfo.InvariantCulture))
						.Append('\n');
				}
			}
			if (TryDay(Plugin.SeasonStart.Value, out var utc))
			{
				int seasonNumber;
				DateTime dateTime3 = Cal.SeasonEnd(utcNow, utc, Plugin.SeasonLengthDays.Value, out seasonNumber);
				if (dateTime3 > utcNow && dateTime3 < dateTime.AddDays(3.0))
				{
					long value = (long)(dateTime3 - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
					stringBuilder.Append("• ⏳ The season ends <t:").Append(value).Append(":R>");
					if (Plugin.FestivalDays.Value > 0)
					{
						stringBuilder.Append(" — the festival runs its last ").Append(Plugin.FestivalDays.Value).Append(" days");
					}
					stringBuilder.Append('\n');
				}
			}
			if (stringBuilder.Length == 0)
			{
				stringBuilder.Append("Nothing on the calendar yet. Press F7 in game to add an event.");
			}
			Post("\ud83d\udcc5 The coming week in Vargheim", stringBuilder.ToString());
			Plugin.Log.LogInfo((object)"Calendar: weekly digest posted.");
		}
	}
	internal static class Ui
	{
		internal static bool Open;

		private static string s_line = "";

		private static float s_lineAt;

		private static DateTime s_month = DateTime.Now.Date;

		private static DateTime s_selected = DateTime.Now.Date;

		private static string s_date = "";

		private static string s_time = "20:00";

		private static string s_hours = "1";

		private static string s_title = "";

		private static string s_place = "";

		private static string s_note = "";

		private static Vector2 s_scroll;

		private static GUIStyle s_lineStyle;

		private static GUIStyle s_h1;

		private static GUIStyle s_h2;

		private static GUIStyle s_text;

		private static GUIStyle s_quiet;

		private static GUIStyle s_cell;

		private static GUIStyle s_cellSel;

		private static GUIStyle s_cellToday;

		private static Texture2D s_fill;

		private static bool s_editing;

		private static bool s_cursorFreed;

		private static RectTransform s_hudPanel;

		private static float s_hudLookAt;

		internal static void Dirty()
		{
			s_lineAt = 0f;
		}

		internal static void Toggle()
		{
			if (!((Object)(object)Player.m_localPlayer == (Object)null))
			{
				Open = !Open;
				if (Open)
				{
					s_month = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
					s_selected = DateTime.Now.Date;
					s_date = s_selected.ToString("yyyy-MM-dd");
					s_note = (Client.HaveData ? "" : "Waiting for the server's calendar...");
				}
			}
		}

		internal static void Tick()
		{
			//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)
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				Open = false;
				return;
			}
			if (!Open)
			{
				s_editing = false;
			}
			if ((!((Object)(object)Chat.instance != (Object)null) || !Chat.instance.HasFocus()) && !Console.IsVisible() && !TextInput.IsVisible() && !s_editing)
			{
				KeyboardShortcut value = Plugin.PanelKey.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					Toggle();
				}
			}
			if (Open && Input.GetKeyDown((KeyCode)27))
			{
				Open = false;
			}
			Mouse();
			if (Time.time >= s_lineAt)
			{
				s_lineAt = Time.time + 2f;
				s_line = Client.HudLine();
			}
		}

		private static void Mouse()
		{
			if (Open)
			{
				s_cursorFreed = true;
			}
			else if (s_cursorFreed)
			{
				s_cursorFreed = false;
				if (!InventoryGui.IsVisible() && !Minimap.IsOpen() && !StoreGui.IsVisible() && !TextInput.IsVisible() && !Console.IsVisible() && (!((Object)(object)Chat.instance != (Object)null) || !Chat.instance.HasFocus()))
				{
					Cursor.lockState = (CursorLockMode)1;
					Cursor.visible = false;
				}
			}
		}

		private static void Styles()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Expected O, but got Unknown
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Expected O, but got Unknown
			//IL_016d: 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)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Expected O, but got Unknown
			//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Expected O, but got Unknown
			if (s_lineStyle == null)
			{
				s_fill = new Texture2D(1, 1, (TextureFormat)4, false);
				s_fill.SetPixel(0, 0, Color.white);
				s_fill.Apply();
				s_lineStyle = new GUIStyle(GUI.skin.label)
				{
					alignment = (TextAnchor)4,
					fontStyle = (FontStyle)1,
					richText = false,
					wordWrap = false
				};
				s_lineStyle.normal.textColor = new Color(0.93f, 0.84f, 0.55f, 0.95f);
				s_h1 = new GUIStyle(GUI.skin.label)
				{
					fontStyle = (FontStyle)1,
					richText = false
				};
				s_h1.normal.textColor = new Color(0.95f, 0.86f, 0.6f);
				s_h2 = new GUIStyle(s_h1);
				s_h2.normal.textColor = new Color(0.9f, 0.9f, 0.85f);
				s_text = new GUIStyle(GUI.skin.label)
				{
					richText = false,
					wordWrap = true
				};
				s_text.normal.textColor = new Color(0.9f, 0.88f, 0.82f);
				s_quiet = new GUIStyle(s_text);
				s_quiet.normal.textColor = new Color(0.68f, 0.64f, 0.56f);
				s_cell = new GUIStyle(GUI.skin.button)
				{
					alignment = (TextAnchor)0,
					richText = false,
					wordWrap = true
				};
				s_cellSel = new GUIStyle(s_cell);
				GUIStyleState normal = s_cellSel.normal;
				GUIStyleState hover = s_cellSel.hover;
				Color textColor = default(Color);
				((Color)(ref textColor))..ctor(1f, 0.85f, 0.45f);
				hover.textColor = textColor;
				normal.textColor = textColor;
				s_cellSel.fontStyle = (FontStyle)1;
				s_cellToday = new GUIStyle(s_cell);
				s_cellToday.fontStyle = (FontStyle)1;
			}
		}

		internal static void Draw()
		{
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: 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_019e: 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_01da: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)Hud.instance == (Object)null)
			{
				return;
			}
			Styles();
			float num = Mathf.Clamp((float)Screen.height / 1080f, 0.6f, 2f);
			if (!Open)
			{
				DrawLine(num);
				return;
			}
			s_lineStyle.fontSize = 0;
			int num2 = Mathf.RoundToInt(14f * num);
			GUIStyle obj = s_text;
			GUIStyle obj2 = s_quiet;
			GUIStyle obj3 = s_cell;
			GUIStyle obj4 = s_cellSel;
			int num3 = (s_cellToday.fontSize = num2);
			int num5 = (obj4.fontSize = num3);
			int num7 = (obj3.fontSize = num5);
			int fontSize = (obj2.fontSize = num7);
			obj.fontSize = fontSize;
			s_h1.fontSize = Mathf.RoundToInt(20f * num);
			s_h2.fontSize = Mathf.RoundToInt(16f * num);
			GUIStyle textField = GUI.skin.textField;
			fontSize = (GUI.skin.button.fontSize = num2);
			textField.fontSize = fontSize;
			float num11 = 980f * num;
			float num12 = 640f * num;
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(((float)Screen.width - num11) * 0.5f, ((float)Screen.height - num12) * 0.5f, num11, num12);
			Color color = GUI.color;
			GUI.color = new Color(0.07f, 0.06f, 0.05f, 0.94f);
			GUI.DrawTexture(val, (Texture)(object)s_fill);
			GUI.color = color;
			GUILayout.BeginArea(new Rect(((Rect)(ref val)).x + 18f * num, ((Rect)(ref val)).y + 14f * num, ((Rect)(ref val)).width - 36f * num, ((Rect)(ref val)).height - 28f * num));
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label("Vargheim calendar", s_h1, Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			GUILayout.Label("Times shown in your local time  ·  " + ((object)Plugin.PanelKey.Value/*cast due to .constrained prefix*/).ToString() + " or Esc closes", s_quiet, Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("Close", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f * num) }))
			{
				Open = false;
			}
			GUILayout.EndHorizontal();
			Summary();
			GUILayout.Space(6f * num);
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(470f * num) });
			Month(num);
			GUILayout.EndVertical();
			GUILayout.Space(16f * num);
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			Day(num);
			GUILayout.EndVertical();
			GUILayout.EndHorizontal();
			GUILayout.EndArea();
		}

		private static RectTransform HudPanel()
		{
			if ((Object)(object)s_hudPanel != (Object)null)
			{
				return s_hudPanel;
			}
			if (Time.time < s_hudLookAt)
			{
				return null;
			}
			s_hudLookAt = Time.time + 5f;
			GameObject val = GameObject.Find("VH_Ring");
			if ((Object)(object)val != (Object)null && (Object)(object)val.transform.parent != (Object)null)
			{
				Transform parent = val.transform.parent;
				s_hudPanel = (RectTransform)(object)((parent is RectTransform) ? parent : null);
			}
			return s_hudPanel;
		}

		private static void DrawLine(float k)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Expected O, but got Unknown
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.ShowHudLine.Value || string.IsNullOrEmpty(s_line) || Hud.IsUserHidden() || (Object)(object)Minimap.instance == (Object)null || (int)Minimap.instance.m_mode != 1 || InventoryGui.IsVisible())
			{
				return;
			}
			RawImage mapImageSmall = Minimap.instance.m_mapImageSmall;
			if (!((Object)(object)mapImageSmall == (Object)null))
			{
				Vector3[] array = (Vector3[])(object)new Vector3[4];
				RectTransform val = HudPanel();
				float x;
				float x2;
				float num;
				if ((Object)(object)val != (Object)null && ((Component)val).gameObject.activeInHierarchy)
				{
					val.GetWorldCorners(array);
					x = array[0].x;
					x2 = array[2].x;
					num = (float)Screen.height - array[0].y + (float)Plugin.HudOffsetY.Value * k;
				}
				else
				{
					((Graphic)mapImageSmall).rectTransform.GetWorldCorners(array);
					x = array[0].x;
					x2 = array[2].x;
					num = (float)Screen.height - array[0].y + ((float)Plugin.HudOffsetY.Value + 30f) * k;
				}
				float num2 = Mathf.Max(x2 - x, 200f * k);
				float num3 = (x + x2) * 0.5f;
				int num4 = Mathf.RoundToInt(12f * k);
				int num5 = Mathf.Max(8, Mathf.RoundToInt(9f * k));
				s_lineStyle.fontSize = num4;
				while (num4 > num5 && s_lineStyle.CalcSize(new GUIContent(s_line)).x > num2)
				{
					num4 = (s_lineStyle.fontSize = num4 - 1);
				}
				Rect val2 = default(Rect);
				((Rect)(ref val2))..ctor(num3 - num2 * 0.5f, num - 4f * k, num2, 17f * k);
				Color color = GUI.color;
				Color textColor = s_lineStyle.normal.textColor;
				GUI.color = new Color(0.06f, 0.07f, 0.09f, 0.62f);
				GUI.DrawTexture(val2, (Texture)(object)s_fill);
				GUI.color = color;
				s_lineStyle.normal.textColor = new Color(0f, 0f, 0f, 0.85f);
				GUI.Label(new Rect(((Rect)(ref val2)).x + 1f, ((Rect)(ref val2)).y + 1f, ((Rect)(ref val2)).width, ((Rect)(ref val2)).height), s_line, s_lineStyle);
				s_lineStyle.normal.textColor = textColor;
				GUI.Label(val2, s_line, s_lineStyle);
			}
		}

		private static void Summary()
		{
			string text = SeasonsBridge.Describe();
			List<string> list = new List<string>();
			if (text.Length > 0)
			{
				list.Add("World: " + text);
			}
			if (Client.Season(out var endUtc, out var number))
			{
				list.Add((number == 0) ? ("The season starts " + Client.Local(endUtc)) : ("Season " + number + " ends " + Client.Local(endUtc) + " (" + Client.Span(endUtc) + ")"));
			}
			if (Client.Festival(out var startUtc, out var _, out var name))
			{
				list.Add(name + " " + ((DateTime.UtcNow >= startUtc) ? "now" : Client.Span(startUtc)));
			}
			GUILayout.Label((list.Count > 0) ? string.Join("   ·   ", list.ToArray()) : (Client.HaveData ? "No season set on the server yet." : "Waiting for the server's calendar..."), s_text, Array.Empty<GUILayoutOption>());
		}

		private static void Month(float k)
		{
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("<", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f * k) }))
			{
				s_month = s_month.AddMonths(-1);
			}
			GUILayout.FlexibleSpace();
			GUILayout.Label(s_month.ToString("MMMM yyyy", CultureInfo.InvariantCulture), s_h2, Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			if (GUILayout.Button(">", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f * k) }))
			{
				s_month = s_month.AddMonths(1);
			}
			GUILayout.EndHorizontal();
			string[] obj = new string[7] { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
			float num = 64f * k;
			float num2 = 62f * k;
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			string[] array = obj;
			for (int i = 0; i < array.Length; i++)
			{
				GUILayout.Label(array[i], s_quiet, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num) });
			}
			GUILayout.EndHorizontal();
			int num3 = (int)(s_month.DayOfWeek + 6) % 7;
			DateTime dateTime = s_month.AddDays(-num3);
			DateTime date = DateTime.Now.Date;
			DateTime startUtc;
			DateTime endUtc;
			string name;
			bool flag = Client.Festival(out startUtc, out endUtc, out name);
			for (int j = 0; j < 6; j++)
			{
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				int num4 = 0;
				while (num4 < 7)
				{
					string text = dateTime.Day.ToString();
					Holiday holiday = Client.HolidayOn(dateTime);
					int count = Client.On(dateTime).Count;
					if (flag && dateTime < endUtc.ToLocalTime().Date.AddDays(1.0) && dateTime.AddDays(1.0) > startUtc.ToLocalTime())
					{
						text += "\n⚔ fest";
					}
					else if (holiday != null)
					{
						text = text + "\n★ " + Short(holiday.Name);
					}
					if (count > 0)
					{
						text = text + "\n● " + count;
					}
					GUIStyle val = ((dateTime == s_selected) ? s_cellSel : ((dateTime == date) ? s_cellToday : s_cell));
					Color color = GUI.color;
					if (dateTime.Month != s_month.Month)
					{
						GUI.color = new Color(1f, 1f, 1f, 0.45f);
					}
					if (GUILayout.Button(text, val, (GUILayoutOption[])(object)new GUILayoutOption[2]
					{
						GUILayout.Width(num),
						GUILayout.Height(num2)
					}))
					{
						s_selected = dateTime;
						s_date = dateTime.ToString("yyyy-MM-dd");
					}
					GUI.color = color;
					num4++;
					dateTime = dateTime.AddDays(1.0);
				}
				GUILayout.EndHorizontal();
			}
			GUILayout.Label("★ holiday   ⚔ festival (last days of the season)   ● events", s_quiet, Array.Empty<GUILayoutOption>());
		}

		private static string Short(string s)
		{
			if (s.Length <= 8)
			{
				return s;
			}
			return s.Substring(0, 7) + ".";
		}

		private static void Day(float k)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.Label(s_selected.ToString("dddd, MMMM d", CultureInfo.InvariantCulture), s_h2, Array.Empty<GUILayoutOption>());
			Holiday holiday = Client.HolidayOn(s_selected);
			if (holiday != null)
			{
				GUILayout.Label("★ " + holiday.Name, s_text, Array.Empty<GUILayoutOption>());
			}
			s_scroll = GUILayout.BeginScrollView(s_scroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(250f * k) });
			List<CalEvent> list = Client.On(s_selected);
			if (list.Count == 0)
			{
				GUILayout.Label("Nothing planned this day.", s_quiet, Array.Empty<GUILayoutOption>());
			}
			foreach (CalEvent item in list)
			{
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				GUILayout.Label(item.Start.ToLocalTime().ToString("HH:mm") + "  " + item.Title + ((item.Minutes > 0) ? ("  (" + Len(item.Minutes) + ")") : ""), s_text, Array.Empty<GUILayoutOption>());
				GUILayout.FlexibleSpace();
				if (Client.CanRemove(item) && GUILayout.Button("Remove", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f * k) }))
				{
					Client.SendRemove(item.Id);
				}
				GUILayout.EndHorizontal();
				GUILayout.Label(((item.Place.Length > 0) ? ("at " + item.Place + "  ·  ") : "") + ((item.Kind == Kind.Player) ? ("posted by " + item.By) : ((item.Kind == Kind.Festival) ? "festival" : "from the admins")) + "  ·  #" + item.Id, s_quiet, Array.Empty<GUILayoutOption>());
			}
			GUILayout.EndScrollView();
			GUILayout.Space(8f * k);
			GUILayout.Label("Add an event (up to " + Client.MaxPerPlayer + " upcoming each)", s_h2, Array.Empty<GUILayoutOption>());
			s_editing = false;
			Field("Date (YYYY-MM-DD)", ref s_date, 130f * k, k);
			Field("Start (HH:MM)", ref s_time, 80f * k, k);
			Field("Hours", ref s_hours, 50f * k, k);
			Field("What", ref s_title, 300f * k, k);
			Field("Where (optional)", ref s_place, 300f * k, k);
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("Add to calendar", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f * k) }))
			{
				float result;
				if (!Cal.TryParseLocal(s_date, s_time, out var local))
				{
					s_note = "Date as 2026-12-20 and time as 20:00, please.";
				}
				else if (!float.TryParse(s_hours, NumberStyles.Float, CultureInfo.InvariantCulture, out result) || result < 0f || result > 24f)
				{
					s_note = "Hours: a number from 0 to 24.";
				}
				else
				{
					s_note = Client.SendAdd(local, Mathf.RoundToInt(result * 60f), s_title, s_place);
					if (s_note.StartsWith("Sent"))
					{
						s_title = "";
						s_place = "";
					}
				}
			}
			GUILayout.Label(s_note, s_quiet, Array.Empty<GUILayoutOption>());
			GUILayout.EndHorizontal();
		}

		private static void Field(string label, ref string value, float width, float k)
		{
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label(label, s_quiet, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f * k) });
			GUI.SetNextControlName("vfest_" + label);
			value = GUILayout.TextField(value ?? "", 60, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(width) });
			if (GUI.GetNameOfFocusedControl() == "vfest_" + label)
			{
				s_editing = true;
			}
			GUILayout.EndHorizontal();
		}

		private static string Len(int m)
		{
			if (m < 60)
			{
				return m + " min";
			}
			return m / 60 + " h" + ((m % 60 > 0) ? (" " + m % 60 + " min") : "");
		}
	}
}