Decompiled source of Namify v0.2.0

plugins/Namify.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Lamb.UI;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Shared;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")]
[assembly: AssemblyCompany("p1xel8ted")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Namify")]
[assembly: AssemblyFileVersion("0.2.0")]
[assembly: AssemblyInformationalVersion("0.2.0+73b9373c9f488bc078394712735d849400edbb39")]
[assembly: AssemblyProduct("Namify")]
[assembly: AssemblyTitle("Namify")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.2.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[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 Shared
{
	internal sealed class ConfigurationManagerAttributes
	{
		public delegate void CustomHotkeyDrawerFunc(ConfigEntryBase setting, ref bool isCurrentlyAcceptingInput);

		public bool? ShowRangeAsPercent;

		public Action<ConfigEntryBase> CustomDrawer;

		public CustomHotkeyDrawerFunc CustomHotkeyDrawer;

		public bool? Browsable;

		public string Category;

		public object DefaultValue;

		public bool? HideDefaultButton;

		public bool? HideSettingName;

		public string Description;

		public string DispName;

		public int? Order;

		public bool? ReadOnly;

		public bool? IsAdvanced;

		public Func<object, string> ObjToStr;

		public Func<string, object> StrToObj;
	}
	public static class Extensions
	{
		public static bool TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
		{
			if (dictionary.ContainsKey(key))
			{
				return false;
			}
			dictionary.Add(key, value);
			return true;
		}

		public static void AddRange<T>(this SortedSet<T> set, IEnumerable<T> elements)
		{
			foreach (T element in elements)
			{
				set.Add(element);
			}
		}

		public static bool TryReplace(this string source, string oldValue, string newValue, out string result)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (oldValue == null)
			{
				throw new ArgumentNullException("oldValue");
			}
			result = source.Replace(oldValue, newValue);
			return (object)source != result;
		}

		public static string GetPath(this GameObject obj)
		{
			if (!((Object)(object)obj.transform.parent == (Object)null))
			{
				return ((Component)obj.transform.parent).gameObject.GetPath() + "/" + ((Object)obj).name;
			}
			return ((Object)obj).name;
		}

		public static bool Contains(this string source, string toCheck, StringComparison comparison)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (toCheck == null)
			{
				throw new ArgumentNullException("toCheck");
			}
			return source.IndexOf(toCheck, comparison) >= 0;
		}
	}
}
namespace Namify
{
	public static class Data
	{
		internal const string NamifyDataPath = "namify_names.json";

		internal const string UserDataPath = "user_names.json";

		public static SortedSet<string> NamifyNames;

		public static SortedSet<string> UserNames;

		private static readonly COTLDataReadWriter<List<string>> NamifyNameReadWriter;

		private static readonly COTLDataReadWriter<List<string>> UserNameReadWriter;

		static Data()
		{
			NamifyNames = new SortedSet<string>();
			UserNames = new SortedSet<string>();
			NamifyNameReadWriter = new COTLDataReadWriter<List<string>>();
			UserNameReadWriter = new COTLDataReadWriter<List<string>>();
			COTLDataReadWriter<List<string>> namifyNameReadWriter = NamifyNameReadWriter;
			((MMDataReadWriterBase<List<string>>)(object)namifyNameReadWriter).OnReadCompleted = (Action<List<string>>)Delegate.Combine(((MMDataReadWriterBase<List<string>>)(object)namifyNameReadWriter).OnReadCompleted, (Action<List<string>>)delegate(List<string> names)
			{
				NamifyNames = new SortedSet<string>(names);
				Plugin.Log.LogInfo((object)((NamifyNames.Count > 0) ? $"Loaded {NamifyNames.Count} Namify generated names." : "No saved names exist."));
				RemoveFollowerNames();
			});
			COTLDataReadWriter<List<string>> namifyNameReadWriter2 = NamifyNameReadWriter;
			((MMDataReadWriterBase<List<string>>)(object)namifyNameReadWriter2).OnReadError = (Action<MMReadWriteError>)Delegate.Combine(((MMDataReadWriterBase<List<string>>)(object)namifyNameReadWriter2).OnReadError, (Action<MMReadWriteError>)delegate
			{
				Plugin.Log.LogWarning((object)"Failed to load saved names!");
			});
			COTLDataReadWriter<List<string>> namifyNameReadWriter3 = NamifyNameReadWriter;
			((MMDataReadWriterBase<List<string>>)(object)namifyNameReadWriter3).OnWriteCompleted = (Action)Delegate.Combine(((MMDataReadWriterBase<List<string>>)(object)namifyNameReadWriter3).OnWriteCompleted, (Action)delegate
			{
				Plugin.Log.LogInfo((object)$"Saved {NamifyNames.Count} Namify generated names!");
			});
			COTLDataReadWriter<List<string>> namifyNameReadWriter4 = NamifyNameReadWriter;
			((MMDataReadWriterBase<List<string>>)(object)namifyNameReadWriter4).OnWriteError = (Action<MMReadWriteError>)Delegate.Combine(((MMDataReadWriterBase<List<string>>)(object)namifyNameReadWriter4).OnWriteError, (Action<MMReadWriteError>)delegate(MMReadWriteError error)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				Plugin.Log.LogWarning((object)("There was an issue saving Namify generated names: " + error.Message));
			});
			COTLDataReadWriter<List<string>> userNameReadWriter = UserNameReadWriter;
			((MMDataReadWriterBase<List<string>>)(object)userNameReadWriter).OnReadCompleted = (Action<List<string>>)Delegate.Combine(((MMDataReadWriterBase<List<string>>)(object)userNameReadWriter).OnReadCompleted, (Action<List<string>>)delegate(List<string> names)
			{
				UserNames = new SortedSet<string>(names);
				Plugin.Log.LogInfo((object)((UserNames.Count > 0) ? $"Loaded {UserNames.Count} user-generated names." : "No saved names exist."));
				RemoveFollowerNames();
			});
			COTLDataReadWriter<List<string>> userNameReadWriter2 = UserNameReadWriter;
			((MMDataReadWriterBase<List<string>>)(object)userNameReadWriter2).OnReadError = (Action<MMReadWriteError>)Delegate.Combine(((MMDataReadWriterBase<List<string>>)(object)userNameReadWriter2).OnReadError, (Action<MMReadWriteError>)delegate
			{
				Plugin.Log.LogWarning((object)"Failed to load saved user-generated names!");
			});
			COTLDataReadWriter<List<string>> userNameReadWriter3 = UserNameReadWriter;
			((MMDataReadWriterBase<List<string>>)(object)userNameReadWriter3).OnWriteCompleted = (Action)Delegate.Combine(((MMDataReadWriterBase<List<string>>)(object)userNameReadWriter3).OnWriteCompleted, (Action)delegate
			{
				Plugin.Log.LogInfo((object)$"Saved {UserNames.Count} user-generated names!");
			});
			COTLDataReadWriter<List<string>> userNameReadWriter4 = UserNameReadWriter;
			((MMDataReadWriterBase<List<string>>)(object)userNameReadWriter4).OnWriteError = (Action<MMReadWriteError>)Delegate.Combine(((MMDataReadWriterBase<List<string>>)(object)userNameReadWriter4).OnWriteError, (Action<MMReadWriteError>)delegate(MMReadWriteError error)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				Plugin.Log.LogWarning((object)("There was an issue saving user-generated names: " + error.Message));
			});
		}

		private static void RemoveFollowerNames()
		{
			foreach (string name in NamifyNames)
			{
				Follower.Followers.RemoveAll((Follower a) => a.Brain.Info.Name == name);
			}
			foreach (string name2 in UserNames)
			{
				Follower.Followers.RemoveAll((Follower a) => a.Brain.Info.Name == name2);
			}
		}

		internal static void LoadData()
		{
			((MMDataReadWriterBase<List<string>>)(object)NamifyNameReadWriter).Read("namify_names.json");
			((MMDataReadWriterBase<List<string>>)(object)UserNameReadWriter).Read("user_names.json");
		}

		internal static void SaveData()
		{
			((MMDataReadWriterBase<List<string>>)(object)NamifyNameReadWriter).Write(NamifyNames.ToList(), "namify_names.json", false, true);
			((MMDataReadWriterBase<List<string>>)(object)UserNameReadWriter).Write(UserNames.ToList(), "user_names.json", false, true);
		}

		internal static void GetNamifyNames(Action onFail = null, Action onComplete = null)
		{
			bool primaryError = false;
			if (NamifyNames.Count > 0)
			{
				return;
			}
			((MonoBehaviour)GameManager.GetInstance()).StartCoroutine(NamifyNamesGetRequest("https://randommer.io/api/Name?nameType=fullname&quantity=1000", apiKey: true, delegate(UnityWebRequest req)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Invalid comparison between Unknown and I4
				Result result = req.result;
				if (result - 2 <= 2)
				{
					Plugin.Log.LogError((object)(req.error + ": " + req.downloadHandler.text));
					NotificationCentre.Instance.PlayGenericNotification("There was an error retrieving names for Namify! Trying back-up source...", (Flair)0);
					onFail?.Invoke();
					primaryError = true;
				}
				else
				{
					string[] array = JsonConvert.DeserializeObject<string[]>(req.downloadHandler.text);
					string[] array2 = array;
					foreach (string text in array2)
					{
						NamifyNames.AddRange(text.Split());
					}
					SaveData();
					NotificationCentre.Instance.PlayGenericNotification("Names retrieved for Namify!", (Flair)0);
					onComplete?.Invoke();
				}
			}));
			if (primaryError)
			{
				((MonoBehaviour)GameManager.GetInstance()).StartCoroutine(GetNamifyNamesBackupRequest(onFail, onComplete));
			}
		}

		private static IEnumerator GetNamifyNamesBackupRequest(Action onFail = null, Action onComplete = null)
		{
			for (int i = 0; i < 10; i++)
			{
				yield return ((MonoBehaviour)GameManager.GetInstance()).StartCoroutine(NamifyNamesGetRequest("https://namey.muffinlabs.com/name.json?count=10&with_surname=true&frequency=all", apiKey: false, delegate(UnityWebRequest req)
				{
					//IL_0001: Unknown result type (might be due to invalid IL or missing references)
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					//IL_0009: Unknown result type (might be due to invalid IL or missing references)
					//IL_000b: Invalid comparison between Unknown and I4
					Result result = req.result;
					if (result - 2 <= 2)
					{
						Plugin.Log.LogError((object)(req.error + ": " + req.downloadHandler.text));
						NotificationCentre.Instance.PlayGenericNotification("There was an error retrieving names for Namify from the backup source!", (Flair)0);
						onFail?.Invoke();
					}
					else
					{
						string[] array = JsonConvert.DeserializeObject<string[]>(req.downloadHandler.text);
						string[] array2 = array;
						foreach (string item in array2)
						{
							NamifyNames.Add(item);
						}
						SaveData();
						NotificationCentre.Instance.PlayGenericNotification("Names retrieved for Namify from the backup source!", (Flair)0);
						onComplete?.Invoke();
					}
				}));
			}
		}

		private static IEnumerator NamifyNamesGetRequest(string endpoint, bool apiKey, Action<UnityWebRequest> callback)
		{
			UnityWebRequest request = UnityWebRequest.Get(endpoint);
			try
			{
				if (apiKey)
				{
					request.SetRequestHeader("X-Api-Key", Plugin.PersonalApiKey.Value);
				}
				yield return request.SendWebRequest();
				callback(request);
			}
			finally
			{
				((IDisposable)request)?.Dispose();
			}
		}
	}
	[Harmony]
	public static class Patches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(SaveAndLoad), "Save")]
		private static void SaveAndLoad_Save()
		{
			if (DataManager.Instance.AllowSaving && !CheatConsole.IN_DEMO)
			{
				Data.SaveData();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(SaveAndLoad), "Load")]
		private static void SaveAndLoad_Load(int saveSlot)
		{
			if (!CheatConsole.IN_DEMO)
			{
				Data.LoadData();
			}
		}

		internal static void CleanNames(int id = -1)
		{
			Dictionary<int, string> dictionary = new Dictionary<int, string>();
			foreach (SimFollower item in FollowerManager.SimFollowers.SelectMany((KeyValuePair<FollowerLocation, List<SimFollower>> a) => a.Value))
			{
				if (item.Brain.Info.Name.TryReplace("*", string.Empty, out var result))
				{
					item.Brain.Info.Name = result;
					Extensions.TryAdd(dictionary, item.Brain.Info.ID, result);
				}
			}
			foreach (Follower item2 in FollowerManager.Followers.SelectMany((KeyValuePair<FollowerLocation, List<Follower>> a) => a.Value))
			{
				if (item2.Brain.Info.Name.TryReplace("*", string.Empty, out var result2))
				{
					item2.Brain.Info.Name = result2;
					Extensions.TryAdd(dictionary, item2.Brain.Info.ID, result2);
				}
			}
			foreach (FollowerInfo follower in DataManager.Instance.Followers)
			{
				if (follower.Name.TryReplace("*", string.Empty, out var result3))
				{
					follower.Name = result3;
					Extensions.TryAdd(dictionary, follower.ID, result3);
				}
			}
			Follower val = FollowerManager.FindFollowerByID(id);
			if (Object.op_Implicit((Object)(object)val) && val.Brain.Info.Name.TryReplace("*", string.Empty, out var result4))
			{
				val.Brain.Info.Name = result4;
				Extensions.TryAdd(dictionary, val.Brain.Info.ID, result4);
			}
			SimFollower val2 = FollowerManager.FindSimFollowerByID(id);
			if (val2 != null && val2.Brain.Info.Name.TryReplace("*", string.Empty, out var result5))
			{
				val2.Brain.Info.Name = result5;
				Extensions.TryAdd(dictionary, val2.Brain.Info.ID, result5);
			}
			foreach (KeyValuePair<int, string> item3 in dictionary)
			{
				Plugin.Log.LogInfo((object)$"Cleaned ID: {item3.Key} Name: {item3.Value}");
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(interaction_FollowerInteraction), "OnInteract")]
		private static void interaction_FollowerInteraction_OnInteract()
		{
			CleanNames();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerFarming), "OnEnable")]
		private static void PlayerFarming_OnEnable()
		{
			CleanNames();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIFollowerIndoctrinationMenuController), "Show", new Type[]
		{
			typeof(Follower),
			typeof(OriginalFollowerLookData),
			typeof(bool)
		})]
		private static void UIFollowerIndoctrinationMenuController_Show(ref UIFollowerIndoctrinationMenuController __instance)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			UIFollowerIndoctrinationMenuController instance = __instance;
			((UnityEvent)((Button)__instance._acceptButton).onClick).AddListener((UnityAction)delegate
			{
				string name = instance._targetFollower.Brain.Info.Name;
				name = name.Replace("*", string.Empty);
				Plugin.Log.LogInfo((object)("Follower name " + name + " confirmed! Removing name from saved name list and cleaning up asterisks if applicable."));
				Data.NamifyNames.Remove(name);
				Data.UserNames.Remove(name);
				instance._targetFollower.Brain.Info.Name = name;
				CleanNames();
			});
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(FollowerInfo), "GenerateName")]
		public static void FollowerInfo_GenerateName(ref string __result)
		{
			if (GameManager.GetInstance() == null || DataManager.Instance == null)
			{
				return;
			}
			if (Data.NamifyNames.Count <= 0)
			{
				Data.GetNamifyNames();
			}
			if (Data.NamifyNames.Count <= 0 && Data.UserNames.Count <= 0)
			{
				Plugin.Log.LogError((object)"No names found!");
				return;
			}
			List<string> list = Data.NamifyNames.Concat(Data.UserNames).Distinct().ToList();
			string text = ListExtensions.RandomElement<string>(list);
			if (Plugin.AsterixNames.Value && !text.Contains("*"))
			{
				text += "*";
			}
			__result = text;
		}
	}
	[BepInPlugin("p1xel8ted.cotl.namify", "Namify", "0.2.0")]
	[BepInDependency("com.bepis.bepinex.configurationmanager", "18.3")]
	public class Plugin : BaseUnityPlugin
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static Action<int> <0>__CleanNames;

			public static FollowerChanged <1>__CleanNames;

			public static Action<ConfigEntryBase> <2>__CleanAsterisks;

			public static Action<ConfigEntryBase> <3>__AddNameButton;

			public static Action<ConfigEntryBase> <4>__OpenNamifyNamesFile;

			public static Action<ConfigEntryBase> <5>__OpenUserGeneratedNamesFile;

			public static Action<ConfigEntryBase> <6>__GenerateNewNamesButton;

			public static Action<ConfigEntryBase> <7>__ReloadNames;
		}

		private const string PluginGuid = "p1xel8ted.cotl.namify";

		internal const string PluginName = "Namify";

		private const string PluginVer = "0.2.0";

		private const string NamesSection = "Names";

		private const string ApiSection = "API";

		public static ManualLogSource Log { get; private set; }

		internal static ConfigEntry<string> PersonalApiKey { get; private set; }

		internal static ConfigEntry<string> AddName { get; private set; }

		internal static ConfigEntry<bool> AsterixNames { get; private set; }

		private static bool ShowGetNewConfirmationDialog { get; set; }

		private static bool ShowReloadConfirmationDialog { get; set; }

		private static string NamifyNamesFilePath => Path.Combine(Application.persistentDataPath, "saves", "namify_names.json");

		private static string UserNameFilePath => Path.Combine(Application.persistentDataPath, "saves", "user_names.json");

		private static PopupManager PopupManagerInstance { get; set; }

		private void Awake()
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			InitializeLogger();
			InitializeConfigurations();
			FollowerBrain.OnBrainAdded = (Action<int>)Delegate.Combine(FollowerBrain.OnBrainAdded, new Action<int>(Patches.CleanNames));
			FollowerChanged onFollowerAdded = FollowerManager.OnFollowerAdded;
			object obj = <>O.<1>__CleanNames;
			if (obj == null)
			{
				FollowerChanged val = Patches.CleanNames;
				<>O.<1>__CleanNames = val;
				obj = (object)val;
			}
			FollowerManager.OnFollowerAdded = (FollowerChanged)Delegate.Combine((Delegate?)(object)onFollowerAdded, (Delegate?)obj);
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "p1xel8ted.cotl.namify");
			Log.LogInfo((object)"Loaded Namify!");
		}

		private void InitializeLogger()
		{
			Log = ((BaseUnityPlugin)this).Logger;
		}

		private void InitializeConfigurations()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Expected O, but got Unknown
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Expected O, but got Unknown
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Expected O, but got Unknown
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0309: Expected O, but got Unknown
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Expected O, but got Unknown
			PopupManagerInstance = ((Component)this).gameObject.AddComponent<PopupManager>();
			AsterixNames = ((BaseUnityPlugin)this).Config.Bind<bool>("Names", "Asterisks Names", false, new ConfigDescription("Namified names will have an asterisk next to them in the UI. Will be removed automatically when the follower is accepted.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 12
				}
			}));
			((BaseUnityPlugin)this).Config.Bind<bool>("Names", "Clean Asterisks", true, new ConfigDescription("Manually run the clean-up names function. Need to be loaded into a save to function.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 11,
					DispName = string.Empty,
					HideDefaultButton = true,
					CustomDrawer = CleanAsterisks
				}
			}));
			PersonalApiKey = ((BaseUnityPlugin)this).Config.Bind<string>("API", "Personal API Key", "ee5f806e1c1d458b99c934c0eb3de5b8", "The default API Key is mine, limited to 1000 requests per day. You can get your own at https://randommer.io/");
			AddName = ((BaseUnityPlugin)this).Config.Bind<string>("Names", "Add Name", "", new ConfigDescription("Adds a name to the list of names.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 10
				}
			}));
			((BaseUnityPlugin)this).Config.Bind<bool>("Names", "Add Name Button", true, new ConfigDescription("Add the name entered to the list.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 9,
					DispName = string.Empty,
					HideDefaultButton = true,
					CustomDrawer = AddNameButton
				}
			}));
			((BaseUnityPlugin)this).Config.Bind<bool>("Names", "Open Namify Names File", true, new ConfigDescription("Opens the Namify generated names file for viewing/editing.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 8,
					DispName = string.Empty,
					HideDefaultButton = true,
					CustomDrawer = OpenNamifyNamesFile
				}
			}));
			((BaseUnityPlugin)this).Config.Bind<bool>("Names", "Open User Names File", true, new ConfigDescription("Opens the user-generated names file for viewing/editing.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 7,
					DispName = string.Empty,
					HideDefaultButton = true,
					CustomDrawer = OpenUserGeneratedNamesFile
				}
			}));
			((BaseUnityPlugin)this).Config.Bind<bool>("Names", "Generate New Names", true, new ConfigDescription("Generates new Namify games. User-generated names are not changed.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 6,
					DispName = string.Empty,
					HideDefaultButton = true,
					CustomDrawer = GenerateNewNamesButton
				}
			}));
			((BaseUnityPlugin)this).Config.Bind<bool>("Names", "Reload Names", true, new ConfigDescription("Reloads names from file.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 5,
					DispName = string.Empty,
					HideDefaultButton = true,
					CustomDrawer = ReloadNames
				}
			}));
		}

		private static void OpenNamifyNamesFile(ConfigEntryBase entry)
		{
			if (GUILayout.Button("Open Namify List", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				TryOpenNamifyNamesFile();
			}
		}

		private static void CleanAsterisks(ConfigEntryBase entry)
		{
			if (GUILayout.Button("Clean Asterisks", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				Patches.CleanNames();
			}
		}

		private static void OpenUserGeneratedNamesFile(ConfigEntryBase entry)
		{
			if (GUILayout.Button("Open User List", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				TryOpenUserNamesFile();
			}
		}

		private static void TryOpenNamifyNamesFile()
		{
			if (File.Exists(NamifyNamesFilePath))
			{
				Application.OpenURL(NamifyNamesFilePath);
			}
			else
			{
				PopupManagerInstance.ShowPopup("Names file (" + NamifyNamesFilePath + ") does not exist!");
			}
		}

		private static void TryOpenUserNamesFile()
		{
			if (File.Exists(UserNameFilePath))
			{
				Application.OpenURL(UserNameFilePath);
			}
			else
			{
				PopupManagerInstance.ShowPopup("Names file (" + UserNameFilePath + ") does not exist!");
			}
		}

		private static void DisplayGetNewConfirmationDialog()
		{
			GUILayout.Label("Are you sure you want to generate new names?", Array.Empty<GUILayoutOption>());
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("Yes", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				GenerateNewNamesAction();
				ShowGetNewConfirmationDialog = false;
			}
			if (GUILayout.Button("No", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				ShowGetNewConfirmationDialog = false;
			}
			GUILayout.EndHorizontal();
		}

		private static void DisplayReloadConfirmationDialog()
		{
			GUILayout.Label("Are you sure you want to reload names from file?", Array.Empty<GUILayoutOption>());
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("Yes", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				try
				{
					Data.LoadData();
					PopupManagerInstance.ShowPopup("Names reloaded from file!");
				}
				catch (Exception ex)
				{
					PopupManagerInstance.ShowPopup("Error in reloading names. Check log for more details.");
					Log.LogError((object)("Error in reloading names: " + ex.Message));
				}
				ShowReloadConfirmationDialog = false;
			}
			if (GUILayout.Button("No", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				ShowReloadConfirmationDialog = false;
			}
			GUILayout.EndHorizontal();
		}

		private static void GenerateNewNamesAction()
		{
			try
			{
				File.Delete(NamifyNamesFilePath);
				Data.NamifyNames.Clear();
				Data.GetNamifyNames(delegate
				{
					PopupManagerInstance.ShowPopup("Error in generating new names!");
				}, delegate
				{
					PopupManagerInstance.ShowPopup("New names generated!");
				});
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Error in generating new names: " + ex.Message));
			}
		}

		private static void AddNameButton(ConfigEntryBase entry)
		{
			if (GUILayout.Button("Add Name", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				if (string.IsNullOrWhiteSpace(AddName.Value))
				{
					PopupManagerInstance.ShowPopup("You haven't entered a name to add?");
					return;
				}
				if (!Data.UserNames.Add(AddName.Value))
				{
					PopupManagerInstance.ShowPopup("'" + AddName.Value + "' already exists!");
					return;
				}
				Data.SaveData();
				PopupManagerInstance.ShowPopup("Added '" + AddName.Value + "' to available names!");
			}
		}

		private static void ReloadNames(ConfigEntryBase entry)
		{
			if (ShowReloadConfirmationDialog)
			{
				DisplayReloadConfirmationDialog();
			}
			else if (GUILayout.Button("Reload Names From File", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				ShowReloadConfirmationDialog = true;
			}
		}

		private static void GenerateNewNamesButton(ConfigEntryBase entry)
		{
			if (ShowGetNewConfirmationDialog)
			{
				DisplayGetNewConfirmationDialog();
			}
			else if (GUILayout.Button("Generate New Names", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				ShowGetNewConfirmationDialog = true;
			}
		}
	}
	internal class PopupManager : MonoBehaviour
	{
		private bool showPopup;

		private string popupMessage = "";

		private Rect popupRect = new Rect((float)Screen.width / 2f - 150f, (float)Screen.height / 2f - 75f, 300f, 100f);

		private GUIStyle messageStyle;

		private void Start()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: 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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			GUIStyle val = new GUIStyle
			{
				alignment = (TextAnchor)4,
				wordWrap = true,
				fontSize = 20
			};
			val.normal.textColor = Color.white;
			messageStyle = val;
		}

		private void OnGUI()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (showPopup)
			{
				popupRect = GUILayout.Window(0, popupRect, new WindowFunction(DrawPopup), "Namify", Array.Empty<GUILayoutOption>());
			}
		}

		private void DrawPopup(int windowID)
		{
			GUILayout.FlexibleSpace();
			GUILayout.Label(popupMessage, messageStyle, Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			if (GUILayout.Button("Close", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) }))
			{
				Plugin.AddName.Value = string.Empty;
				showPopup = false;
			}
			GUILayout.FlexibleSpace();
			GUILayout.EndHorizontal();
			GUILayout.FlexibleSpace();
		}

		public void ShowPopup(string message)
		{
			popupMessage = message;
			showPopup = true;
		}
	}
}