Decompiled source of GreydwarfWorkers v3.7.3

BepInEx/plugins/GreydwarfWorkers/GreydwarfWorkers.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Jotunn.Managers;
using Splatform;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("GreydwarfWorkers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GreydwarfWorkers")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5fe28502-d2ff-414f-a3ea-6261dfdcc2e4")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace GreydwarfWorkers;

public static class FarmCropCatalog
{
	private static readonly List<FarmCropDefinition> s_crops = new List<FarmCropDefinition>();

	private static readonly Dictionary<string, FarmCropDefinition> s_cropsByGrownPrefabName = new Dictionary<string, FarmCropDefinition>();

	private static bool s_initialized = false;

	public static IReadOnlyList<FarmCropDefinition> Crops
	{
		get
		{
			EnsureInitialized();
			return s_crops;
		}
	}

	public static void EnsureInitialized()
	{
		if (s_initialized)
		{
			return;
		}
		s_crops.Clear();
		if ((Object)(object)ObjectDB.instance == (Object)null)
		{
			return;
		}
		GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("Cultivator");
		if ((Object)(object)itemPrefab == (Object)null)
		{
			return;
		}
		ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
		if ((Object)(object)component == (Object)null || component.m_itemData == null || component.m_itemData.m_shared == null)
		{
			return;
		}
		PieceTable buildPieces = component.m_itemData.m_shared.m_buildPieces;
		if ((Object)(object)buildPieces == (Object)null || buildPieces.m_pieces == null)
		{
			return;
		}
		for (int i = 0; i < buildPieces.m_pieces.Count; i++)
		{
			GameObject val = buildPieces.m_pieces[i];
			if ((Object)(object)val == (Object)null)
			{
				continue;
			}
			Plant component2 = val.GetComponent<Plant>();
			if ((Object)(object)component2 == (Object)null || !component2.m_needCultivatedGround || component2.m_grownPrefabs == null || component2.m_grownPrefabs.Length == 0)
			{
				continue;
			}
			for (int j = 0; j < component2.m_grownPrefabs.Length; j++)
			{
				GameObject val2 = component2.m_grownPrefabs[j];
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				Pickable component3 = val2.GetComponent<Pickable>();
				if ((Object)(object)component3 == (Object)null)
				{
					continue;
				}
				string harvestItemName = null;
				if ((Object)(object)component3.m_itemPrefab != (Object)null)
				{
					harvestItemName = ((Object)component3.m_itemPrefab).name;
				}
				Piece component4 = val.GetComponent<Piece>();
				string plantItemName = null;
				int plantItemAmount = 0;
				if ((Object)(object)component4 != (Object)null && component4.m_resources != null && component4.m_resources.Length != 0)
				{
					Requirement val3 = component4.m_resources[0];
					if (val3 != null)
					{
						if ((Object)(object)val3.m_resItem != (Object)null)
						{
							plantItemName = ((Object)val3.m_resItem).name;
						}
						plantItemAmount = val3.m_amount;
					}
				}
				FarmCropDefinition farmCropDefinition = new FarmCropDefinition(val, val2, plantItemName, plantItemAmount, harvestItemName, component2.m_growRadius);
				s_crops.Add(farmCropDefinition);
				s_cropsByGrownPrefabName[((Object)val2).name] = farmCropDefinition;
				s_cropsByGrownPrefabName[((Object)val2).name + "(Clone)"] = farmCropDefinition;
			}
		}
		s_initialized = true;
	}

	public static bool TryGetCropByGrownPrefabName(string prefabName, out FarmCropDefinition crop)
	{
		EnsureInitialized();
		crop = null;
		if (string.IsNullOrEmpty(prefabName))
		{
			return false;
		}
		return s_cropsByGrownPrefabName.TryGetValue(prefabName, out crop);
	}

	public static void Reset()
	{
		s_crops.Clear();
		s_initialized = false;
	}
}
public sealed class FarmCropDefinition
{
	public GameObject PlantPrefab { get; }

	public GameObject GrownPrefab { get; }

	public string PlantItemName { get; }

	public int PlantItemAmount { get; }

	public string HarvestItemName { get; }

	public float GrowRadius { get; }

	public FarmCropDefinition(GameObject plantPrefab, GameObject grownPrefab, string plantItemName, int plantItemAmount, string harvestItemName, float growRadius)
	{
		PlantPrefab = plantPrefab;
		GrownPrefab = grownPrefab;
		PlantItemName = plantItemName;
		PlantItemAmount = plantItemAmount;
		HarvestItemName = harvestItemName;
		GrowRadius = growRadius;
	}
}
public static class FarmCropScanner
{
	private static Pickable[] s_pickableCache;

	private static float s_pickableCacheNextRefreshTime;

	private const float PickableCacheRefreshInterval = 1f;

	private static Pickable[] GetPickableCache()
	{
		if (s_pickableCache == null || Time.time >= s_pickableCacheNextRefreshTime)
		{
			s_pickableCache = Object.FindObjectsByType<Pickable>((FindObjectsSortMode)0);
			s_pickableCacheNextRefreshTime = Time.time + 1f;
		}
		return s_pickableCache;
	}

	public static void ResetCache()
	{
		s_pickableCache = null;
		s_pickableCacheNextRefreshTime = 0f;
	}

	public static void FindHarvestableCrops(FarmField field, List<Pickable> results)
	{
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		if (results == null)
		{
			return;
		}
		results.Clear();
		if (field == null)
		{
			return;
		}
		Pickable[] pickableCache = GetPickableCache();
		foreach (Pickable val in pickableCache)
		{
			if (!((Object)(object)val == (Object)null) && ((Component)val).gameObject.activeInHierarchy && val.m_harvestable && val.CanBePicked() && field.IsInside(((Component)val).transform.position))
			{
				results.Add(val);
			}
		}
	}
}
public sealed class FarmField
{
	private static readonly Vector2Int[] s_directions = (Vector2Int[])(object)new Vector2Int[4]
	{
		new Vector2Int(1, 0),
		new Vector2Int(-1, 0),
		new Vector2Int(0, 1),
		new Vector2Int(0, -1)
	};

	private readonly Heightmap m_heightmap;

	private readonly HashSet<Vector2Int> m_cells;

	public Heightmap Heightmap => m_heightmap;

	public int CellCount => m_cells.Count;

	private FarmField(Heightmap heightmap, HashSet<Vector2Int> cells)
	{
		m_heightmap = heightmap;
		m_cells = cells;
	}

	public bool IsInside(Vector3 worldPos)
	{
		//IL_001c: 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_004e: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)m_heightmap == (Object)null)
		{
			return false;
		}
		if (!m_heightmap.IsPointInside(worldPos, 0f))
		{
			return false;
		}
		int num = default(int);
		int num2 = default(int);
		m_heightmap.WorldToVertexMask(worldPos, ref num, ref num2);
		return m_cells.Contains(new Vector2Int(num, num2));
	}

	public IEnumerable<Vector2Int> GetCells()
	{
		return m_cells;
	}

	public static bool TryCreate(Vector3 worldPos, out FarmField field)
	{
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: 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)
		//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_013e: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0162: 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_0180: 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)
		field = null;
		Heightmap val = Heightmap.FindHeightmap(worldPos);
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		Texture2D paintMask = val.GetPaintMask();
		if ((Object)(object)paintMask == (Object)null)
		{
			return false;
		}
		int num = default(int);
		int num2 = default(int);
		val.WorldToVertexMask(worldPos, ref num, ref num2);
		if (num < 0 || num2 < 0 || num >= ((Texture)paintMask).width || num2 >= ((Texture)paintMask).height)
		{
			return false;
		}
		Color paintMask2 = val.GetPaintMask(num, num2);
		if (paintMask2.g <= 0.5f)
		{
			return false;
		}
		HashSet<Vector2Int> hashSet = new HashSet<Vector2Int>();
		Queue<Vector2Int> queue = new Queue<Vector2Int>();
		Vector2Int item = default(Vector2Int);
		((Vector2Int)(ref item))..ctor(num, num2);
		hashSet.Add(item);
		queue.Enqueue(item);
		while (queue.Count > 0)
		{
			Vector2Int val2 = queue.Dequeue();
			for (int i = 0; i < s_directions.Length; i++)
			{
				Vector2Int item2 = val2 + s_directions[i];
				if (((Vector2Int)(ref item2)).x >= 0 && ((Vector2Int)(ref item2)).y >= 0 && ((Vector2Int)(ref item2)).x < ((Texture)paintMask).width && ((Vector2Int)(ref item2)).y < ((Texture)paintMask).height && !hashSet.Contains(item2))
				{
					Color paintMask3 = val.GetPaintMask(((Vector2Int)(ref item2)).x, ((Vector2Int)(ref item2)).y);
					if (!(paintMask3.g <= 0.5f))
					{
						hashSet.Add(item2);
						queue.Enqueue(item2);
					}
				}
			}
		}
		field = new FarmField(val, hashSet);
		return true;
	}
}
public static class FarmHarvester
{
	public static bool TryFindNearestCrop(FarmField field, Vector3 fromPosition, List<Pickable> candidates, out Pickable nearestCrop)
	{
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		nearestCrop = null;
		if (field == null || candidates == null)
		{
			return false;
		}
		FarmCropScanner.FindHarvestableCrops(field, candidates);
		if (candidates.Count == 0)
		{
			return false;
		}
		float num = float.MaxValue;
		for (int i = 0; i < candidates.Count; i++)
		{
			Pickable val = candidates[i];
			if (!((Object)(object)val == (Object)null) && FarmCropCatalog.TryGetCropByGrownPrefabName(((Object)((Component)val).gameObject).name, out var _))
			{
				Vector3 val2 = ((Component)val).transform.position - fromPosition;
				float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
				if (sqrMagnitude < num)
				{
					num = sqrMagnitude;
					nearestCrop = val;
				}
			}
		}
		return (Object)(object)nearestCrop != (Object)null;
	}

	public static bool TryHarvest(Pickable pickable, Humanoid humanoid)
	{
		if ((Object)(object)pickable == (Object)null || (Object)(object)humanoid == (Object)null)
		{
			return false;
		}
		if (!((Component)pickable).gameObject.activeInHierarchy)
		{
			return false;
		}
		if (!pickable.m_harvestable || !pickable.CanBePicked())
		{
			return false;
		}
		pickable.Interact(humanoid, false, false);
		return true;
	}
}
public static class FarmPlanter
{
	private static readonly MethodInfo HaveGrowSpaceMethod = typeof(Plant).GetMethod("HaveGrowSpace", BindingFlags.Instance | BindingFlags.NonPublic);

	public unsafe static bool TrySpawnPlantOnServer(string prefabName, Vector3 position, Quaternion rotation)
	{
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_013e: Unknown result type (might be due to invalid IL or missing references)
		//IL_025b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0260: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
		{
			Debug.LogError((object)"[Greydwarf Workers] Plant spawn rejected: this machine is not the server.");
			return false;
		}
		if ((Object)(object)ZNetScene.instance == (Object)null || string.IsNullOrEmpty(prefabName))
		{
			return false;
		}
		FarmCropCatalog.EnsureInitialized();
		bool flag = false;
		foreach (FarmCropDefinition crop in FarmCropCatalog.Crops)
		{
			if (crop != null && (Object)(object)crop.PlantPrefab != (Object)null && ((Object)crop.PlantPrefab).name == prefabName)
			{
				flag = true;
				break;
			}
		}
		if (!flag)
		{
			Debug.LogWarning((object)("[Greydwarf Workers] Server rejected unsupported planting prefab '" + prefabName + "'."));
			return false;
		}
		GameObject prefab = ZNetScene.instance.GetPrefab(prefabName);
		if ((Object)(object)prefab == (Object)null || (Object)(object)prefab.GetComponent<Plant>() == (Object)null)
		{
			Debug.LogWarning((object)("[Greydwarf Workers] Server could not find a valid plant prefab '" + prefabName + "'."));
			return false;
		}
		GameObject val = NetworkInstantiate(prefab, position, rotation);
		if ((Object)(object)val == (Object)null)
		{
			Debug.LogError((object)("[Greydwarf Workers] Server could not instantiate '" + prefabName + "'."));
			return false;
		}
		ZNetView component = val.GetComponent<ZNetView>();
		if ((Object)(object)component == (Object)null || !component.IsValid() || component.GetZDO() == null)
		{
			Debug.LogError((object)("[Greydwarf Workers] Server instantiation of '" + prefabName + "' did not produce a valid ZNetView and ZDO. The plant will not be reported as successfully planted."));
			CleanupFailedServerPlant(val);
			return false;
		}
		if (!FinalizeSpawnedPlant(val))
		{
			Debug.LogError((object)("[Greydwarf Workers] Server could not establish ownership for plant '" + prefabName + "'."));
			CleanupFailedServerPlant(val);
			return false;
		}
		Plant component2 = val.GetComponent<Plant>();
		if (!HasVanillaGrowSpace(component2))
		{
			Debug.LogWarning((object)("[Greydwarf Workers] Server rejected plant '" + prefabName + "': vanilla HaveGrowSpace() returned false."));
			CleanupFailedServerPlant(val);
			return false;
		}
		ZDO zDO = component.GetZDO();
		string[] obj = new string[11]
		{
			"[Greydwarf Workers] SERVER created plant '", prefabName, "'. ZDO=", null, null, null, null, null, null, null,
			null
		};
		ZDOID uid = zDO.m_uid;
		obj[3] = ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString();
		obj[4] = ", Owner=";
		obj[5] = zDO.GetOwner().ToString();
		obj[6] = ", Persistent=";
		obj[7] = zDO.Persistent.ToString();
		obj[8] = ", Position=";
		Vector3 val2 = position;
		obj[9] = ((object)(*(Vector3*)(&val2))/*cast due to .constrained prefix*/).ToString();
		obj[10] = ".";
		Debug.Log((object)string.Concat(obj));
		return true;
	}

	private static void CleanupFailedServerPlant(GameObject planted)
	{
		if ((Object)(object)planted == (Object)null)
		{
			return;
		}
		ZNetView component = planted.GetComponent<ZNetView>();
		if ((Object)(object)component != (Object)null && component.IsValid())
		{
			if (!component.IsOwner())
			{
				component.ClaimOwnership();
			}
			if (component.IsOwner())
			{
				component.Destroy();
				return;
			}
		}
		Object.Destroy((Object)(object)planted);
	}

	public static bool TryPlantOne(FarmCropDefinition crop, Vector3 position, Quaternion rotation, WorkerInventory inventory)
	{
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		//IL_019a: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_032e: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0305: Unknown result type (might be due to invalid IL or missing references)
		if (crop == null || (Object)(object)crop.PlantPrefab == (Object)null || (Object)(object)inventory == (Object)null)
		{
			return false;
		}
		if (crop.PlantItemAmount <= 0 || string.IsNullOrEmpty(crop.PlantItemName))
		{
			return false;
		}
		Plant component = crop.PlantPrefab.GetComponent<Plant>();
		if ((Object)(object)component == (Object)null)
		{
			Debug.LogWarning((object)("[Greydwarf Workers] Plant prefab '" + ((Object)crop.PlantPrefab).name + "' has no Plant component."));
			return false;
		}
		if ((Object)(object)ObjectDB.instance == (Object)null)
		{
			return false;
		}
		GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(crop.PlantItemName);
		if ((Object)(object)itemPrefab == (Object)null)
		{
			Debug.LogWarning((object)("[Greydwarf Workers] Could not find planting item prefab '" + crop.PlantItemName + "'."));
			return false;
		}
		ItemDrop component2 = itemPrefab.GetComponent<ItemDrop>();
		if ((Object)(object)component2 == (Object)null || component2.m_itemData == null || component2.m_itemData.m_shared == null)
		{
			Debug.LogWarning((object)("[Greydwarf Workers] Planting item '" + crop.PlantItemName + "' has no valid ItemDrop data."));
			return false;
		}
		string name = component2.m_itemData.m_shared.m_name;
		if (string.IsNullOrEmpty(name))
		{
			return false;
		}
		if (inventory.GetAmount(name) < crop.PlantItemAmount)
		{
			return false;
		}
		Heightmap val = Heightmap.FindHeightmap(position);
		if ((Object)(object)val == (Object)null || !val.IsCultivated(position))
		{
			return false;
		}
		GameObject val2 = NetworkInstantiate(crop.PlantPrefab, position, rotation);
		if ((Object)(object)val2 == (Object)null)
		{
			return false;
		}
		if (!FinalizeSpawnedPlant(val2))
		{
			Debug.LogWarning((object)("[Greydwarf Workers] Plant '" + ((Object)crop.PlantPrefab).name + "' was spawned, but ownership could not be established."));
			return false;
		}
		Plant component3 = val2.GetComponent<Plant>();
		if (!HasVanillaGrowSpace(component3))
		{
			Debug.Log((object)("[Greydwarf Workers] Cannot plant '" + ((Object)crop.PlantPrefab).name + "': vanilla HaveGrowSpace() rejected the position."));
			ZNetView component4 = val2.GetComponent<ZNetView>();
			if ((Object)(object)component4 != (Object)null && component4.IsValid())
			{
				component4.Destroy();
			}
			return false;
		}
		if (!inventory.RemoveItem(name, crop.PlantItemAmount))
		{
			Debug.LogError((object)("[Greydwarf Workers] Plant '" + ((Object)crop.PlantPrefab).name + "' was spawned, but the seed could not be removed from the worker inventory."));
			return false;
		}
		Piece component5 = crop.PlantPrefab.GetComponent<Piece>();
		if ((Object)(object)component5 != (Object)null && component5.m_placeEffect != null)
		{
			component5.m_placeEffect.Create(position, rotation, (Transform)null, 1f, -1, default(ZDOID));
		}
		Debug.Log((object)("[Greydwarf Workers] " + $"Planted '{((Object)crop.PlantPrefab).name}' at {position} using {crop.PlantItemAmount}x {name}."));
		return true;
	}

	private static GameObject NetworkInstantiate(GameObject prefab, Vector3 position, Quaternion rotation)
	{
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)prefab == (Object)null || (Object)(object)ZNetScene.instance == (Object)null)
		{
			return null;
		}
		GameObject prefab2 = ZNetScene.instance.GetPrefab(((Object)prefab).name);
		if ((Object)(object)prefab2 == (Object)null)
		{
			Debug.LogWarning((object)("[Greydwarf Workers] Could not find network prefab '" + ((Object)prefab).name + "' in ZNetScene."));
			return null;
		}
		try
		{
			return Object.Instantiate<GameObject>(prefab2, position, rotation);
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("[Greydwarf Workers] Failed to instantiate plant '" + ((Object)prefab).name + "': " + ex.Message));
			return null;
		}
	}

	private static bool FinalizeSpawnedPlant(GameObject planted)
	{
		if ((Object)(object)planted == (Object)null)
		{
			return false;
		}
		ZNetView component = planted.GetComponent<ZNetView>();
		if ((Object)(object)component == (Object)null || !component.IsValid())
		{
			return false;
		}
		if (!component.IsOwner())
		{
			component.ClaimOwnership();
		}
		return component.IsOwner();
	}

	private static bool HasVanillaGrowSpace(Plant plant)
	{
		if ((Object)(object)plant == (Object)null || HaveGrowSpaceMethod == null)
		{
			return false;
		}
		try
		{
			object obj = HaveGrowSpaceMethod.Invoke(plant, null);
			bool flag = default(bool);
			int num;
			if (obj is bool)
			{
				flag = (bool)obj;
				num = 1;
			}
			else
			{
				num = 0;
			}
			return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("[Greydwarf Workers] Failed to call Plant.HaveGrowSpace(): " + ex.Message));
			return false;
		}
	}
}
public static class FarmPlantPositionScanner
{
	private static float SearchSpacing => GreydwarfWorkersConfig.EffectiveFarmPlantSearchSpacing;

	public static void FindCandidatePositions(FarmField field, Vector3 fromPosition, List<Vector3> positions)
	{
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0153: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0171: Unknown result type (might be due to invalid IL or missing references)
		//IL_0183: Unknown result type (might be due to invalid IL or missing references)
		//IL_0195: Unknown result type (might be due to invalid IL or missing references)
		//IL_022d: Unknown result type (might be due to invalid IL or missing references)
		//IL_023b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0251: Unknown result type (might be due to invalid IL or missing references)
		//IL_025f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01db: Unknown result type (might be due to invalid IL or missing references)
		//IL_028f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0294: Unknown result type (might be due to invalid IL or missing references)
		//IL_029d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
		if (positions == null)
		{
			return;
		}
		positions.Clear();
		if (field == null || (Object)(object)field.Heightmap == (Object)null)
		{
			return;
		}
		Heightmap heightmap = field.Heightmap;
		int width = heightmap.m_width;
		float scale = heightmap.m_scale;
		if (width <= 0 || scale <= 0f)
		{
			return;
		}
		bool flag = false;
		int num = int.MaxValue;
		int num2 = int.MinValue;
		int num3 = int.MaxValue;
		int num4 = int.MinValue;
		foreach (Vector2Int cell in field.GetCells())
		{
			Vector2Int current = cell;
			flag = true;
			if (((Vector2Int)(ref current)).x < num)
			{
				num = ((Vector2Int)(ref current)).x;
			}
			if (((Vector2Int)(ref current)).x > num2)
			{
				num2 = ((Vector2Int)(ref current)).x;
			}
			if (((Vector2Int)(ref current)).y < num3)
			{
				num3 = ((Vector2Int)(ref current)).y;
			}
			if (((Vector2Int)(ref current)).y > num4)
			{
				num4 = ((Vector2Int)(ref current)).y;
			}
		}
		if (!flag)
		{
			return;
		}
		Vector3 position = ((Component)heightmap).transform.position;
		float num5 = (float)width / 2f;
		float num6 = position.x + ((float)num - num5) * scale;
		float num7 = position.x + ((float)num2 - num5) * scale;
		float num8 = position.z + ((float)num3 - num5) * scale;
		float num9 = position.z + ((float)num4 - num5) * scale;
		Vector3 groundPosition = default(Vector3);
		for (float num10 = num6; num10 <= num7; num10 += SearchSpacing)
		{
			for (float num11 = num8; num11 <= num9; num11 += SearchSpacing)
			{
				((Vector3)(ref groundPosition))..ctor(num10, fromPosition.y, num11);
				if (field.IsInside(groundPosition) && TryGetGroundPosition(heightmap, groundPosition, out groundPosition))
				{
					positions.Add(groundPosition);
				}
			}
		}
		bool flag2 = Mathf.Abs(fromPosition.x - num6) <= Mathf.Abs(fromPosition.x - num7);
		bool startFromMinZ = Mathf.Abs(fromPosition.z - num8) <= Mathf.Abs(fromPosition.z - num9);
		List<float> candidateRows = new List<float>();
		foreach (Vector3 position2 in positions)
		{
			if (!candidateRows.Contains(position2.x))
			{
				candidateRows.Add(position2.x);
			}
		}
		candidateRows.Sort();
		if (!flag2)
		{
			candidateRows.Reverse();
		}
		positions.Sort(delegate(Vector3 a, Vector3 b)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			int num12 = candidateRows.IndexOf(a.x);
			int value = candidateRows.IndexOf(b.x);
			int num13 = num12.CompareTo(value);
			return (num13 != 0) ? num13 : (((num12 % 2 == 0) ? startFromMinZ : (!startFromMinZ)) ? a.z.CompareTo(b.z) : b.z.CompareTo(a.z));
		});
	}

	private static bool TryGetGroundPosition(Heightmap heightmap, Vector3 position, out Vector3 groundPosition)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0003: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		groundPosition = position;
		if ((Object)(object)heightmap == (Object)null)
		{
			return false;
		}
		int width = heightmap.m_width;
		float scale = heightmap.m_scale;
		Vector3 position2 = ((Component)heightmap).transform.position;
		float num = (position.x - position2.x) / scale + (float)width * 0.5f;
		float num2 = (position.z - position2.z) / scale + (float)width * 0.5f;
		if (num < 0f || num > (float)width || num2 < 0f || num2 > (float)width)
		{
			return false;
		}
		int num3 = Mathf.Clamp(Mathf.FloorToInt(num), 0, width - 1);
		int num4 = Mathf.Clamp(Mathf.FloorToInt(num2), 0, width - 1);
		int num5 = Mathf.Min(num3 + 1, width);
		int num6 = Mathf.Min(num4 + 1, width);
		float num7 = num - (float)num3;
		float num8 = num2 - (float)num4;
		float height = heightmap.GetHeight(num3, num4);
		float height2 = heightmap.GetHeight(num5, num4);
		float height3 = heightmap.GetHeight(num3, num6);
		float height4 = heightmap.GetHeight(num5, num6);
		float num9 = Mathf.Lerp(height, height2, num7);
		float num10 = Mathf.Lerp(height3, height4, num7);
		float num11 = Mathf.Lerp(num9, num10, num8);
		groundPosition.y = position2.y + num11;
		return true;
	}
}
public enum GatherResourceType
{
	Wood,
	Stone,
	Coal,
	FineWood,
	CoreWood,
	YggdrasilWood,
	Ashwood,
	Timberwood,
	Copper,
	Tin,
	Bronze,
	Iron,
	Silver,
	BlackMetal,
	Flametal,
	Bloodgold
}
public class GatherResourceDefinition
{
	public GatherResourceType Type { get; }

	public string ItemName { get; }

	public string DisplayName { get; }

	public GatherResourceDefinition(GatherResourceType type, string itemName, string displayName)
	{
		Type = type;
		ItemName = itemName;
		DisplayName = displayName;
	}
}
public static class GreydwarfWorkersConfig
{
	public static ConfigEntry<float> TamingSpeedMultiplier;

	public static ConfigEntry<float> FedDuration;

	public static ConfigEntry<bool> EnableFulingTaming;

	public static ConfigEntry<float> ChestSearchRange;

	public static ConfigEntry<float> ChestSearchInterval;

	public static ConfigEntry<float> ResourceSearchRange;

	public static ConfigEntry<float> ResourceSearchInterval;

	public static ConfigEntry<float> ResourceCollectRange;

	public static ConfigEntry<float> SmelterWaitInterval;

	public static ConfigEntry<float> OreSmelterWaitInterval;

	public static ConfigEntry<float> FireplaceWaitInterval;

	public static ConfigEntry<float> KilnWaitInterval;

	public static ConfigEntry<float> RepairWaitInterval;

	public static ConfigEntry<float> FarmHarvestDropSearchRange;

	public static ConfigEntry<float> FarmSeedChestSearchRange;

	public static ConfigEntry<float> FarmSeedChestSearchInterval;

	public static ConfigEntry<float> FarmPlantSearchSpacing;

	public static ConfigEntry<int> DefaultResourceCapacity;

	public static ConfigEntry<int> WoodCapacity;

	public static ConfigEntry<int> StoneCapacity;

	public static ConfigEntry<int> CoalCapacity;

	public static ConfigEntry<int> IngotCapacity;

	private static bool m_serverConfigApplied;

	private static float m_serverTamingSpeedMultiplier;

	private static float m_serverFedDuration;

	private static bool m_serverEnableFulingTaming;

	private static float m_serverChestSearchRange;

	private static float m_serverChestSearchInterval;

	private static float m_serverResourceSearchRange;

	private static float m_serverResourceSearchInterval;

	private static float m_serverResourceCollectRange;

	private static float m_serverSmelterWaitInterval;

	private static float m_serverOreSmelterWaitInterval;

	private static float m_serverFireplaceWaitInterval;

	private static float m_serverKilnWaitInterval;

	private static float m_serverRepairWaitInterval;

	private static float m_serverFarmHarvestDropSearchRange;

	private static float m_serverFarmSeedChestSearchRange;

	private static float m_serverFarmSeedChestSearchInterval;

	private static float m_serverFarmPlantSearchSpacing;

	private static int m_serverDefaultResourceCapacity;

	private static int m_serverWoodCapacity;

	private static int m_serverStoneCapacity;

	private static int m_serverCoalCapacity;

	private static int m_serverIngotCapacity;

	public static bool ServerConfigApplied => m_serverConfigApplied;

	public static float EffectiveTamingSpeedMultiplier => m_serverConfigApplied ? m_serverTamingSpeedMultiplier : TamingSpeedMultiplier.Value;

	public static float EffectiveFedDuration => m_serverConfigApplied ? m_serverFedDuration : FedDuration.Value;

	public static bool EffectiveEnableFulingTaming => m_serverConfigApplied ? m_serverEnableFulingTaming : EnableFulingTaming.Value;

	public static float EffectiveChestSearchRange => m_serverConfigApplied ? m_serverChestSearchRange : ChestSearchRange.Value;

	public static float EffectiveChestSearchInterval => m_serverConfigApplied ? m_serverChestSearchInterval : ChestSearchInterval.Value;

	public static float EffectiveResourceSearchRange => m_serverConfigApplied ? m_serverResourceSearchRange : ResourceSearchRange.Value;

	public static float EffectiveResourceSearchInterval => m_serverConfigApplied ? m_serverResourceSearchInterval : ResourceSearchInterval.Value;

	public static float EffectiveResourceCollectRange => m_serverConfigApplied ? m_serverResourceCollectRange : ResourceCollectRange.Value;

	public static float EffectiveSmelterWaitInterval => m_serverConfigApplied ? m_serverSmelterWaitInterval : SmelterWaitInterval.Value;

	public static float EffectiveOreSmelterWaitInterval => m_serverConfigApplied ? m_serverOreSmelterWaitInterval : OreSmelterWaitInterval.Value;

	public static float EffectiveFireplaceWaitInterval => m_serverConfigApplied ? m_serverFireplaceWaitInterval : FireplaceWaitInterval.Value;

	public static float EffectiveKilnWaitInterval => m_serverConfigApplied ? m_serverKilnWaitInterval : KilnWaitInterval.Value;

	public static float EffectiveRepairWaitInterval => m_serverConfigApplied ? m_serverRepairWaitInterval : RepairWaitInterval.Value;

	public static float EffectiveFarmHarvestDropSearchRange => m_serverConfigApplied ? m_serverFarmHarvestDropSearchRange : FarmHarvestDropSearchRange.Value;

	public static float EffectiveFarmSeedChestSearchRange => m_serverConfigApplied ? m_serverFarmSeedChestSearchRange : FarmSeedChestSearchRange.Value;

	public static float EffectiveFarmSeedChestSearchInterval => m_serverConfigApplied ? m_serverFarmSeedChestSearchInterval : FarmSeedChestSearchInterval.Value;

	public static float EffectiveFarmPlantSearchSpacing => m_serverConfigApplied ? m_serverFarmPlantSearchSpacing : FarmPlantSearchSpacing.Value;

	public static int EffectiveDefaultResourceCapacity => m_serverConfigApplied ? m_serverDefaultResourceCapacity : DefaultResourceCapacity.Value;

	public static int EffectiveWoodCapacity => m_serverConfigApplied ? m_serverWoodCapacity : WoodCapacity.Value;

	public static int EffectiveStoneCapacity => m_serverConfigApplied ? m_serverStoneCapacity : StoneCapacity.Value;

	public static int EffectiveCoalCapacity => m_serverConfigApplied ? m_serverCoalCapacity : CoalCapacity.Value;

	public static int EffectiveIngotCapacity => m_serverConfigApplied ? m_serverIngotCapacity : IngotCapacity.Value;

	public static string SerializeServerConfig()
	{
		return string.Join("|", TamingSpeedMultiplier.Value, FedDuration.Value, ChestSearchRange.Value, ChestSearchInterval.Value, ResourceSearchRange.Value, ResourceSearchInterval.Value, ResourceCollectRange.Value, SmelterWaitInterval.Value, OreSmelterWaitInterval.Value, FireplaceWaitInterval.Value, KilnWaitInterval.Value, RepairWaitInterval.Value, DefaultResourceCapacity.Value, WoodCapacity.Value, StoneCapacity.Value, CoalCapacity.Value, IngotCapacity.Value, EnableFulingTaming.Value, FarmHarvestDropSearchRange.Value, FarmSeedChestSearchRange.Value, FarmSeedChestSearchInterval.Value, FarmPlantSearchSpacing.Value);
	}

	public static void ApplyServerConfig(string data)
	{
		string[] array = data.Split(new char[1] { '|' });
		if (array.Length == 17 || array.Length == 18 || array.Length == 22)
		{
			int num = 0;
			m_serverTamingSpeedMultiplier = float.Parse(array[num++]);
			m_serverFedDuration = float.Parse(array[num++]);
			m_serverChestSearchRange = float.Parse(array[num++]);
			m_serverChestSearchInterval = float.Parse(array[num++]);
			m_serverResourceSearchRange = float.Parse(array[num++]);
			m_serverResourceSearchInterval = float.Parse(array[num++]);
			m_serverResourceCollectRange = float.Parse(array[num++]);
			m_serverSmelterWaitInterval = float.Parse(array[num++]);
			m_serverOreSmelterWaitInterval = float.Parse(array[num++]);
			m_serverFireplaceWaitInterval = float.Parse(array[num++]);
			m_serverKilnWaitInterval = float.Parse(array[num++]);
			m_serverRepairWaitInterval = float.Parse(array[num++]);
			m_serverDefaultResourceCapacity = int.Parse(array[num++]);
			m_serverWoodCapacity = int.Parse(array[num++]);
			m_serverStoneCapacity = int.Parse(array[num++]);
			m_serverCoalCapacity = int.Parse(array[num++]);
			m_serverIngotCapacity = int.Parse(array[num++]);
			if (array.Length >= 18)
			{
				m_serverEnableFulingTaming = bool.Parse(array[num++]);
			}
			else
			{
				m_serverEnableFulingTaming = true;
			}
			if (array.Length == 22)
			{
				m_serverFarmHarvestDropSearchRange = float.Parse(array[num++]);
				m_serverFarmSeedChestSearchRange = float.Parse(array[num++]);
				m_serverFarmSeedChestSearchInterval = float.Parse(array[num++]);
				m_serverFarmPlantSearchSpacing = float.Parse(array[num++]);
			}
			else
			{
				m_serverFarmHarvestDropSearchRange = FarmHarvestDropSearchRange.Value;
				m_serverFarmSeedChestSearchRange = FarmSeedChestSearchRange.Value;
				m_serverFarmSeedChestSearchInterval = FarmSeedChestSearchInterval.Value;
				m_serverFarmPlantSearchSpacing = FarmPlantSearchSpacing.Value;
			}
			m_serverConfigApplied = true;
		}
	}

	public static void ResetServerConfig()
	{
		m_serverConfigApplied = false;
	}

	public static void Initialize(ConfigFile config)
	{
		TamingSpeedMultiplier = config.Bind<float>("Taming", "TamingSpeedMultiplier", 1f, "Taming speed multiplier. 1.0 = normal speed, 2.0 = twice as fast, 0.5 = half speed.");
		FedDuration = config.Bind<float>("Taming", "FedDuration", 600f, "Duration in seconds that a fed worker remains fed.");
		EnableFulingTaming = config.Bind<bool>("Taming", "EnableFulingTaming", true, "Whether Fulings can be tamed and used as workers.");
		ChestSearchRange = config.Bind<float>("Worker", "ChestSearchRange", 30f, "Maximum distance in meters at which workers search for chests and world workstations.");
		ChestSearchInterval = config.Bind<float>("Worker", "ChestSearchInterval", 5f, "Interval in seconds between searches for chests and world workstations.");
		ResourceSearchRange = config.Bind<float>("Worker", "ResourceSearchRange", 20f, "Maximum distance in meters at which workers search for dropped resources.");
		ResourceSearchInterval = config.Bind<float>("Worker", "ResourceSearchInterval", 2f, "Interval in seconds between searches for dropped resources.");
		ResourceCollectRange = config.Bind<float>("Worker", "ResourceCollectRange", 2.5f, "Distance in meters at which a worker can collect or interact with a target.");
		SmelterWaitInterval = config.Bind<float>("Worker", "SmelterWaitInterval", 15f, "How long a worker waits before retrying a full or unavailable smelter.");
		OreSmelterWaitInterval = config.Bind<float>("Worker", "OreSmelterWaitInterval", 30f, "How long a worker waits before retrying an unavailable ore smelter.");
		FireplaceWaitInterval = config.Bind<float>("Worker", "FireplaceWaitInterval", 30f, "How long a worker waits before searching for a lightsource that needs fuel again.");
		KilnWaitInterval = config.Bind<float>("Worker", "KilnWaitInterval", 15f, "How long a worker waits before retrying a full charcoal kiln.");
		RepairWaitInterval = config.Bind<float>("Worker", "RepairWaitInterval", 15f, "How long a worker waits before searching for damaged structures again.");
		DefaultResourceCapacity = config.Bind<int>("Inventory", "DefaultResourceCapacity", 20, "Maximum amount of a resource a worker can carry when no special capacity is configured.");
		WoodCapacity = config.Bind<int>("Inventory", "WoodCapacity", 20, "Maximum amount of wood a worker can carry.");
		StoneCapacity = config.Bind<int>("Inventory", "StoneCapacity", 20, "Maximum amount of stone a worker can carry.");
		CoalCapacity = config.Bind<int>("Inventory", "CoalCapacity", 20, "Maximum amount of coal a worker can carry.");
		IngotCapacity = config.Bind<int>("Inventory", "IngotCapacity", 10, "Maximum amount of ingots a worker can carry.");
		FarmHarvestDropSearchRange = config.Bind<float>("Farming", "FarmHarvestDropSearchRange", 10f, "Maximum distance in meters at which a worker searches for items dropped by harvesting.");
		FarmSeedChestSearchRange = config.Bind<float>("Farming", "FarmSeedChestSearchRange", 30f, "Maximum distance in meters at which a planting worker searches for a chest containing the required seeds.");
		FarmSeedChestSearchInterval = config.Bind<float>("Farming", "FarmSeedChestSearchInterval", 60f, "How often in seconds a planting worker retries searching for a chest containing the required seeds.");
		FarmPlantSearchSpacing = config.Bind<float>("Farming", "FarmPlantSearchSpacing", 1f, "Distance in meters between candidate positions when scanning a field for planting locations. Lower values find positions more precisely but increase scan cost.");
	}
}
public class GreydwarfWorkerUI : MonoBehaviour
{
	private enum WorkerJob
	{
		Gathering,
		RefuelSmelter,
		PutOreInSmelter,
		RefuelLightsources,
		RefuelCharcoalKiln,
		RepairStructures,
		Harvest,
		Plant
	}

	private GameObject m_panel;

	private GameObject m_workerList;

	private GameObject m_inventoryPanel;

	private GameObject m_inventoryList;

	private GameObject m_jobPanel;

	private GameObject m_jobList;

	private GameObject m_mapTrackingButton;

	private ScrollRect m_workerScrollRect;

	private ScrollRect m_inventoryScrollRect;

	private GreydwarfWorker m_selectedWorker;

	private GreydwarfWorkersPlugin m_plugin;

	private float m_inventoryRefreshTimer = 0f;

	private float m_workerListRefreshTimer = 0f;

	private Text m_jobStatusText;

	private Text m_gatherResourceText;

	private Text m_farmCropText;

	private const float PanelWidth = 700f;

	private const float PanelHeight = 600f;

	private const float InventoryPanelWidth = 600f;

	private const float InventoryPanelHeight = 550f;

	private const float InventoryRefreshInterval = 0.25f;

	private const float WorkerListRefreshInterval = 0.5f;

	private const float RowHeight = 60f;

	private const float RowSpacing = 10f;

	private const float JobPanelWidth = 600f;

	private const float JobPanelHeight = 700f;

	private const float JobButtonHeight = 50f;

	private const float JobButtonSpacing = 12f;

	private readonly Dictionary<string, Text> m_inventoryAmountTexts = new Dictionary<string, Text>();

	private readonly Dictionary<GreydwarfWorker, Text> m_workerStateTexts = new Dictionary<GreydwarfWorker, Text>();

	public static bool IsOpen { get; private set; }

	public static bool SuppressGameMenu { get; private set; }

	private void Awake()
	{
	}

	private void Update()
	{
		if ((Object)(object)m_jobPanel != (Object)null && m_jobPanel.activeSelf)
		{
			UpdateGatherResourceButton();
			UpdateFarmCropButton();
			RefreshJobStatus();
		}
		if ((Object)(object)m_inventoryPanel != (Object)null && m_inventoryPanel.activeSelf)
		{
			m_inventoryRefreshTimer += Time.deltaTime;
			if (m_inventoryRefreshTimer >= 0.25f)
			{
				m_inventoryRefreshTimer = 0f;
				UpdateInventoryAmounts();
			}
		}
		if ((Object)(object)m_panel != (Object)null && m_panel.activeSelf)
		{
			m_workerListRefreshTimer += Time.deltaTime;
			if (m_workerListRefreshTimer >= 0.5f)
			{
				m_workerListRefreshTimer = 0f;
				UpdateWorkerListStatuses();
			}
		}
		if (Input.GetKeyDown((KeyCode)27))
		{
			SuppressGameMenu = true;
			if ((Object)(object)m_jobPanel != (Object)null && m_jobPanel.activeSelf)
			{
				CloseJobMenu();
			}
			else if ((Object)(object)m_inventoryPanel != (Object)null && m_inventoryPanel.activeSelf)
			{
				CloseInventory();
			}
			else if ((Object)(object)m_panel != (Object)null && m_panel.activeSelf)
			{
				Close();
			}
		}
	}

	private void LateUpdate()
	{
		SuppressGameMenu = false;
	}

	public void Initialize(GreydwarfWorkersPlugin plugin)
	{
		m_plugin = plugin;
	}

	public void Toggle()
	{
		if ((Object)(object)m_jobPanel != (Object)null && m_jobPanel.activeSelf)
		{
			CloseJobMenu();
			return;
		}
		if ((Object)(object)m_inventoryPanel != (Object)null && m_inventoryPanel.activeSelf)
		{
			CloseInventory();
			return;
		}
		if ((Object)(object)m_panel == (Object)null)
		{
			CreateUI();
		}
		if (!((Object)(object)m_panel == (Object)null))
		{
			bool flag = !m_panel.activeSelf;
			if (flag)
			{
				m_workerListRefreshTimer = 0f;
				RefreshWorkerList();
			}
			m_panel.SetActive(flag);
			IsOpen = flag;
		}
	}

	public void Close()
	{
		if ((Object)(object)m_inventoryPanel != (Object)null)
		{
			m_inventoryPanel.SetActive(false);
		}
		if ((Object)(object)m_panel != (Object)null)
		{
			m_panel.SetActive(false);
			IsOpen = false;
		}
		if ((Object)(object)m_jobPanel != (Object)null)
		{
			m_jobPanel.SetActive(false);
		}
		m_selectedWorker = null;
	}

	private void CreateUI()
	{
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)m_panel != (Object)null))
		{
			if (GUIManager.Instance == null)
			{
				Debug.LogError((object)"[Greydwarf Workers] GUIManager is not available.");
				return;
			}
			if ((Object)(object)GUIManager.CustomGUIFront == (Object)null)
			{
				Debug.LogError((object)"[Greydwarf Workers] CustomGUIFront is not available.");
				return;
			}
			m_panel = GUIManager.Instance.CreateWoodpanel(GUIManager.CustomGUIFront.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, 0f), 700f, 600f, true);
			((Object)m_panel).name = "GreydwarfWorkerPanel";
			CreateTitle();
			CreateCloseButton();
			CreateWorkerList();
			CreateMapTrackingButton();
			CreateInventoryPanel();
			CreateJobPanel();
			m_panel.SetActive(false);
		}
	}

	private void CreateTitle()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: 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: Unknown result type (might be due to invalid IL or missing references)
		GUIManager.Instance.CreateText("GREYDWARF WORKERS", m_panel.transform, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, -45f), GUIManager.Instance.AveriaSerifBold, 30, GUIManager.Instance.ValheimOrange, true, Color.black, 500f, 45f, false);
	}

	private void CreateCloseButton()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Expected O, but got Unknown
		GameObject val = GUIManager.Instance.CreateButton("X", m_panel.transform, new Vector2(1f, 1f), new Vector2(1f, 1f), new Vector2(-35f, -35f), 50f, 50f);
		((Object)val).name = "GreydwarfWorkerCloseButton";
		Button component = val.GetComponent<Button>();
		if ((Object)(object)component != (Object)null)
		{
			((UnityEvent)component.onClick).AddListener(new UnityAction(Close));
		}
	}

	private void CreateMapTrackingButton()
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Expected O, but got Unknown
		m_mapTrackingButton = GUIManager.Instance.CreateButton("Worker Map Pins: ON", m_panel.transform, new Vector2(0.5f, 0f), new Vector2(0.5f, 0f), new Vector2(0f, 35f), 250f, 42f);
		((Object)m_mapTrackingButton).name = "GreydwarfMapTrackingButton";
		Button component = m_mapTrackingButton.GetComponent<Button>();
		if ((Object)(object)component != (Object)null)
		{
			((UnityEvent)component.onClick).AddListener((UnityAction)delegate
			{
				if (!((Object)(object)m_plugin == (Object)null))
				{
					m_plugin.ToggleWorkerMapTrackingGlobally();
					RefreshMapTrackingButtonLabel();
				}
			});
		}
		RefreshMapTrackingButtonLabel();
	}

	private void RefreshMapTrackingButtonLabel()
	{
		if (!((Object)(object)m_mapTrackingButton == (Object)null) && !((Object)(object)m_plugin == (Object)null))
		{
			Text componentInChildren = m_mapTrackingButton.GetComponentInChildren<Text>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.text = (m_plugin.WorkerMapTrackingGloballyEnabled ? "Worker Map Pins: ON" : "Worker Map Pins: OFF");
			}
		}
	}

	private void CreateWorkerList()
	{
		//IL_0022: 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_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bb: 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_01c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01de: Unknown result type (might be due to invalid IL or missing references)
		//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0202: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = GUIManager.Instance.CreateScrollView(m_panel.transform, false, true, 12f, 5f, GUIManager.Instance.ValheimScrollbarHandleColorBlock, new Color(0f, 0f, 0f, 0.15f), 640f, 470f);
		((Object)val).name = "GreydwarfWorkerScrollView";
		RectTransform component = val.GetComponent<RectTransform>();
		component.anchoredPosition = new Vector2(0f, -20f);
		m_workerScrollRect = val.GetComponentInChildren<ScrollRect>(true);
		Scrollbar verticalScrollbar = m_workerScrollRect.verticalScrollbar;
		if ((Object)(object)verticalScrollbar != (Object)null)
		{
			RectTransform component2 = ((Component)verticalScrollbar).GetComponent<RectTransform>();
			component2.anchoredPosition = new Vector2(3f, component2.anchoredPosition.y);
		}
		if ((Object)(object)m_workerScrollRect == (Object)null || (Object)(object)m_workerScrollRect.content == (Object)null)
		{
			Debug.LogError((object)"[Greydwarf Workers] Failed to create worker scroll view.");
			return;
		}
		m_workerScrollRect.horizontal = false;
		m_workerScrollRect.vertical = true;
		m_workerScrollRect.movementType = (MovementType)2;
		m_workerScrollRect.scrollSensitivity = 35f;
		m_workerList = ((Component)m_workerScrollRect.content).gameObject;
		VerticalLayoutGroup component3 = m_workerList.GetComponent<VerticalLayoutGroup>();
		if ((Object)(object)component3 != (Object)null)
		{
			((Behaviour)component3).enabled = false;
		}
		ContentSizeFitter component4 = m_workerList.GetComponent<ContentSizeFitter>();
		if ((Object)(object)component4 != (Object)null)
		{
			((Behaviour)component4).enabled = false;
		}
		RectTransform component5 = m_workerList.GetComponent<RectTransform>();
		component5.anchorMin = new Vector2(0.5f, 0.5f);
		component5.anchorMax = new Vector2(0.5f, 0.5f);
		component5.pivot = new Vector2(0.5f, 0.5f);
		component5.anchoredPosition = Vector2.zero;
		component5.sizeDelta = new Vector2(640f, 470f);
	}

	private void RefreshWorkerList()
	{
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_0197: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)m_workerList == (Object)null)
		{
			return;
		}
		ClearWorkerList();
		List<Character> allCharacters = Character.GetAllCharacters();
		List<GreydwarfWorker> list = new List<GreydwarfWorker>();
		foreach (Character item in allCharacters)
		{
			if (!((Object)(object)item == (Object)null))
			{
				GreydwarfWorker component = ((Component)item).GetComponent<GreydwarfWorker>();
				Tameable component2 = ((Component)item).GetComponent<Tameable>();
				if (!((Object)(object)component == (Object)null) && !((Object)(object)component2 == (Object)null) && component2.IsTamed())
				{
					list.Add(component);
				}
			}
		}
		list.Sort(delegate(GreydwarfWorker a, GreydwarfWorker b)
		{
			Character component4 = ((Component)a).GetComponent<Character>();
			Character component5 = ((Component)b).GetComponent<Character>();
			string x = (((Object)(object)component4 != (Object)null) ? component4.GetHoverName() : "Greydwarf");
			string y = (((Object)(object)component5 != (Object)null) ? component5.GetHoverName() : "Greydwarf");
			return StringComparer.OrdinalIgnoreCase.Compare(x, y);
		});
		float num = (float)list.Count * 70f;
		float num2 = 470f;
		float num3 = Mathf.Max(num2, num);
		RectTransform component3 = m_workerList.GetComponent<RectTransform>();
		component3.sizeDelta = new Vector2(640f, num3);
		float num4 = num * 0.5f - 30f;
		for (int num5 = 0; num5 < list.Count; num5++)
		{
			CreateWorkerRow(list[num5], num4 - (float)num5 * 70f);
		}
		if (list.Count == 0)
		{
			GUIManager.Instance.CreateText("No tamed Workers found.", m_workerList.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, 0f), GUIManager.Instance.AveriaSerif, 22, Color.white, true, Color.black, 500f, 40f, false);
		}
		if ((Object)(object)m_workerScrollRect != (Object)null)
		{
			m_workerScrollRect.verticalNormalizedPosition = 1f;
		}
	}

	private void CreateWorkerRow(GreydwarfWorker worker, float yPosition)
	{
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Expected O, but got Unknown
		//IL_00f8: 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_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_0139: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: 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_0190: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01de: 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_01fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_020d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0213: Unknown result type (might be due to invalid IL or missing references)
		//IL_0241: Unknown result type (might be due to invalid IL or missing references)
		//IL_0250: Unknown result type (might be due to invalid IL or missing references)
		//IL_025f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0270: Unknown result type (might be due to invalid IL or missing references)
		//IL_0276: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_02db: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_0372: Unknown result type (might be due to invalid IL or missing references)
		//IL_0381: Unknown result type (might be due to invalid IL or missing references)
		//IL_0390: Unknown result type (might be due to invalid IL or missing references)
		//IL_034b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0355: Expected O, but got Unknown
		//IL_03f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03fb: Expected O, but got Unknown
		//IL_0443: Unknown result type (might be due to invalid IL or missing references)
		//IL_0452: Unknown result type (might be due to invalid IL or missing references)
		//IL_0461: Unknown result type (might be due to invalid IL or missing references)
		//IL_04cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d7: Expected O, but got Unknown
		Character component = ((Component)worker).GetComponent<Character>();
		string text = (((Object)(object)component != (Object)null) ? component.GetHoverName() : "Greydwarf");
		string text2 = (((Object)(object)component != (Object)null) ? $"{component.GetHealth():0} / {component.GetMaxHealth():0}" : "0 / 0");
		string text3;
		if (worker.IsWorking)
		{
			text3 = "Working";
		}
		else
		{
			MonsterAI val = (((Object)(object)component != (Object)null) ? ((Component)component).GetComponent<MonsterAI>() : null);
			text3 = ((!((Object)(object)val != (Object)null) || !((Object)(object)val.GetFollowTarget() != (Object)null)) ? "Inactive" : "Following");
		}
		GameObject val2 = new GameObject("GreydwarfWorkerRow");
		val2.transform.SetParent(m_workerList.transform, false);
		RectTransform val3 = val2.AddComponent<RectTransform>();
		val3.anchorMin = new Vector2(0.5f, 0.5f);
		val3.anchorMax = new Vector2(0.5f, 0.5f);
		val3.pivot = new Vector2(0.5f, 0.5f);
		val3.anchoredPosition = new Vector2(0f, yPosition);
		val3.sizeDelta = new Vector2(620f, 60f);
		GUIManager.Instance.CreateText(text, val2.transform, new Vector2(0f, 0.5f), new Vector2(0f, 0.5f), new Vector2(140f, 0f), GUIManager.Instance.AveriaSerifBold, 22, Color.white, true, Color.black, 220f, 35f, false);
		GUIManager.Instance.CreateText("HP: " + text2, val2.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(-40f, 10f), GUIManager.Instance.AveriaSerif, 18, Color.white, true, Color.black, 180f, 30f, false);
		Text component2 = GUIManager.Instance.CreateText(text3, val2.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(-40f, -12f), GUIManager.Instance.AveriaSerif, 17, Color.white, true, Color.black, 180f, 28f, false).GetComponent<Text>();
		if ((Object)(object)component2 != (Object)null)
		{
			m_workerStateTexts[worker] = component2;
		}
		GameObject val4 = GUIManager.Instance.CreateButton("Inventory", val2.transform, new Vector2(1f, 0.5f), new Vector2(1f, 0.5f), new Vector2(-220f, 0f), 140f, 45f);
		((Object)val4).name = "GreydwarfInventoryButton";
		Button component3 = val4.GetComponent<Button>();
		if ((Object)(object)component3 != (Object)null)
		{
			GreydwarfWorker selectedWorker = worker;
			((UnityEvent)component3.onClick).AddListener((UnityAction)delegate
			{
				OpenInventory(selectedWorker);
			});
		}
		GameObject val5 = GUIManager.Instance.CreateButton("Job", val2.transform, new Vector2(1f, 0.5f), new Vector2(1f, 0.5f), new Vector2(-90f, 0f), 100f, 45f);
		((Object)val5).name = "GreydwarfJobButton";
		Button component4 = val5.GetComponent<Button>();
		if ((Object)(object)component4 != (Object)null)
		{
			GreydwarfWorker selectedWorker2 = worker;
			((UnityEvent)component4.onClick).AddListener((UnityAction)delegate
			{
				OpenJobMenu(selectedWorker2);
			});
		}
		bool flag = (Object)(object)m_plugin != (Object)null && m_plugin.IsWorkerMapTrackingEnabled(worker);
		GameObject mapTrackingButtonObject = GUIManager.Instance.CreateButton(flag ? "✓" : "○", val2.transform, new Vector2(1f, 0.5f), new Vector2(1f, 0.5f), new Vector2(-10f, 0f), 40f, 40f);
		((Object)mapTrackingButtonObject).name = "GreydwarfMapTrackingButton";
		Button component5 = mapTrackingButtonObject.GetComponent<Button>();
		if (!((Object)(object)component5 != (Object)null))
		{
			return;
		}
		GreydwarfWorker selectedWorker3 = worker;
		((UnityEvent)component5.onClick).AddListener((UnityAction)delegate
		{
			if (!((Object)(object)m_plugin == (Object)null))
			{
				bool flag2 = m_plugin.ToggleWorkerMapTracking(selectedWorker3);
				Text componentInChildren = mapTrackingButtonObject.GetComponentInChildren<Text>(true);
				if ((Object)(object)componentInChildren != (Object)null)
				{
					componentInChildren.text = (flag2 ? "✓" : "X");
				}
			}
		});
	}

	private void OpenJobMenu(GreydwarfWorker worker)
	{
		if ((Object)(object)worker == (Object)null || (Object)(object)m_jobPanel == (Object)null)
		{
			return;
		}
		m_selectedWorker = worker;
		UpdateGatherResourceButton();
		UpdateFarmCropButton();
		RefreshJobStatus();
		Character component = ((Component)worker).GetComponent<Character>();
		string text = (((Object)(object)component != (Object)null) ? component.GetHoverName() : "Greydwarf");
		Transform val = m_jobPanel.transform.Find("GreydwarfJobTitle");
		if ((Object)(object)val != (Object)null)
		{
			Text component2 = ((Component)val).GetComponent<Text>();
			if ((Object)(object)component2 != (Object)null)
			{
				component2.text = text + "'s JOBS";
			}
		}
		m_panel.SetActive(false);
		m_jobPanel.SetActive(true);
	}

	private void CloseJobMenu()
	{
		if ((Object)(object)m_jobPanel != (Object)null)
		{
			m_jobPanel.SetActive(false);
		}
		m_selectedWorker = null;
		if ((Object)(object)m_panel != (Object)null)
		{
			m_panel.SetActive(true);
			RefreshWorkerList();
		}
	}

	private void OnJobSelected(WorkerJob job)
	{
		if ((Object)(object)m_selectedWorker == (Object)null)
		{
			return;
		}
		if ((Object)(object)m_plugin == (Object)null)
		{
			Debug.LogError((object)"[Greydwarf Workers] Plugin reference is missing.");
			return;
		}
		switch (job)
		{
		case WorkerJob.Gathering:
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.Gathering);
			break;
		case WorkerJob.RefuelSmelter:
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.RefuelSmelter);
			break;
		case WorkerJob.PutOreInSmelter:
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.PutOreInSmelter);
			break;
		case WorkerJob.RefuelLightsources:
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.RefuelLightsources);
			break;
		case WorkerJob.RefuelCharcoalKiln:
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.RefuelCharcoalKiln);
			break;
		case WorkerJob.RepairStructures:
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.RepairStructures);
			break;
		case WorkerJob.Harvest:
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.Harvest);
			break;
		case WorkerJob.Plant:
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.Plant);
			break;
		}
		CloseJobMenu();
	}

	private void CreateInventoryPanel()
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: 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_0171: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Expected O, but got Unknown
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0207: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Expected O, but got Unknown
		//IL_030b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0322: Unknown result type (might be due to invalid IL or missing references)
		//IL_0339: Unknown result type (might be due to invalid IL or missing references)
		//IL_0346: Unknown result type (might be due to invalid IL or missing references)
		//IL_035d: Unknown result type (might be due to invalid IL or missing references)
		m_inventoryPanel = GUIManager.Instance.CreateWoodpanel(GUIManager.CustomGUIFront.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, 0f), 600f, 550f, true);
		((Object)m_inventoryPanel).name = "GreydwarfInventoryPanel";
		GameObject val = GUIManager.Instance.CreateText("INVENTORY", m_inventoryPanel.transform, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, -45f), GUIManager.Instance.AveriaSerifBold, 30, GUIManager.Instance.ValheimOrange, true, Color.black, 400f, 45f, false);
		((Object)val).name = "GreydwarfInventoryTitle";
		GameObject val2 = GUIManager.Instance.CreateButton("X", m_inventoryPanel.transform, new Vector2(1f, 1f), new Vector2(1f, 1f), new Vector2(-35f, -35f), 50f, 50f);
		((Object)val2).name = "GreydwarfInventoryCloseButton";
		Button component = val2.GetComponent<Button>();
		if ((Object)(object)component != (Object)null)
		{
			((UnityEvent)component.onClick).AddListener(new UnityAction(CloseInventory));
		}
		m_inventoryList = new GameObject("GreydwarfInventoryList");
		m_inventoryList.transform.SetParent(m_inventoryPanel.transform, false);
		GameObject val3 = GUIManager.Instance.CreateScrollView(m_inventoryPanel.transform, false, true, 12f, 5f, GUIManager.Instance.ValheimScrollbarHandleColorBlock, new Color(0f, 0f, 0f, 0.15f), 540f, 420f);
		((Object)val3).name = "GreydwarfInventoryScrollView";
		RectTransform component2 = val3.GetComponent<RectTransform>();
		component2.anchoredPosition = new Vector2(0f, -15f);
		m_inventoryScrollRect = val3.GetComponentInChildren<ScrollRect>(true);
		if ((Object)(object)m_inventoryScrollRect == (Object)null || (Object)(object)m_inventoryScrollRect.content == (Object)null)
		{
			Debug.LogError((object)"[Greydwarf Workers] Failed to create inventory scroll view.");
			return;
		}
		m_inventoryScrollRect.horizontal = false;
		m_inventoryScrollRect.vertical = true;
		m_inventoryScrollRect.movementType = (MovementType)2;
		m_inventoryScrollRect.scrollSensitivity = 35f;
		m_inventoryList = ((Component)m_inventoryScrollRect.content).gameObject;
		VerticalLayoutGroup component3 = m_inventoryList.GetComponent<VerticalLayoutGroup>();
		if ((Object)(object)component3 != (Object)null)
		{
			((Behaviour)component3).enabled = false;
		}
		ContentSizeFitter component4 = m_inventoryList.GetComponent<ContentSizeFitter>();
		if ((Object)(object)component4 != (Object)null)
		{
			((Behaviour)component4).enabled = false;
		}
		RectTransform component5 = m_inventoryList.GetComponent<RectTransform>();
		component5.anchorMin = new Vector2(0.5f, 0.5f);
		component5.anchorMax = new Vector2(0.5f, 0.5f);
		component5.pivot = new Vector2(0.5f, 0.5f);
		component5.anchoredPosition = Vector2.zero;
		component5.sizeDelta = new Vector2(540f, 420f);
		m_inventoryPanel.SetActive(false);
	}

	private void OpenInventory(GreydwarfWorker worker)
	{
		if (!((Object)(object)worker == (Object)null) && !((Object)(object)m_inventoryPanel == (Object)null))
		{
			m_selectedWorker = worker;
			m_inventoryRefreshTimer = 0f;
			RefreshInventory();
			m_panel.SetActive(false);
			m_inventoryPanel.SetActive(true);
			if ((Object)(object)m_inventoryScrollRect != (Object)null)
			{
				m_inventoryScrollRect.verticalNormalizedPosition = 1f;
			}
		}
	}

	private void RefreshInventory()
	{
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)m_inventoryList == (Object)null || (Object)(object)m_selectedWorker == (Object)null)
		{
			return;
		}
		ClearInventoryList();
		Character component = ((Component)m_selectedWorker).GetComponent<Character>();
		string text = (((Object)(object)component != (Object)null) ? component.GetHoverName() : "Greydwarf");
		Transform val = m_inventoryPanel.transform.Find("GreydwarfInventoryTitle");
		if ((Object)(object)val != (Object)null)
		{
			Text component2 = ((Component)val).GetComponent<Text>();
			if ((Object)(object)component2 != (Object)null)
			{
				component2.text = text + "'s INVENTORY";
			}
		}
		WorkerInventory component3 = ((Component)m_selectedWorker).GetComponent<WorkerInventory>();
		if ((Object)(object)component3 == (Object)null || component3.IsEmpty())
		{
			GUIManager.Instance.CreateText("Inventory is empty.", m_inventoryList.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, 0f), GUIManager.Instance.AveriaSerif, 22, Color.white, true, Color.black, 450f, 40f, false);
			return;
		}
		Dictionary<string, int> allItems = component3.GetAllItems();
		float num = (float)allItems.Count * 70f;
		RectTransform component4 = m_inventoryList.GetComponent<RectTransform>();
		component4.sizeDelta = new Vector2(540f, Mathf.Max(420f, num));
		float num2 = num * 0.5f - 30f;
		int num3 = 0;
		foreach (KeyValuePair<string, int> item in allItems)
		{
			CreateInventoryRow(component3, item.Key, item.Value, num2 - (float)num3 * 70f);
			num3++;
		}
	}

	private void CreateInventoryRow(WorkerInventory inventory, string itemName, int amount, float yPosition)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Expected O, but got Unknown
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0134: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_0163: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject("GreydwarfInventoryRow");
		val.transform.SetParent(m_inventoryList.transform, false);
		RectTransform val2 = val.AddComponent<RectTransform>();
		val2.anchorMin = new Vector2(0.5f, 0.5f);
		val2.anchorMax = new Vector2(0.5f, 0.5f);
		val2.pivot = new Vector2(0.5f, 0.5f);
		val2.anchoredPosition = new Vector2(0f, yPosition);
		val2.sizeDelta = new Vector2(500f, 60f);
		string displayItemName = GetDisplayItemName(itemName);
		int capacity = inventory.GetCapacity(itemName);
		GUIManager.Instance.CreateText(displayItemName, val.transform, new Vector2(0f, 0.5f), new Vector2(0f, 0.5f), new Vector2(120f, 0f), GUIManager.Instance.AveriaSerifBold, 21, Color.white, true, Color.black, 250f, 35f, false);
		GameObject val3 = GUIManager.Instance.CreateText(amount + " / " + capacity, val.transform, new Vector2(1f, 0.5f), new Vector2(1f, 0.5f), new Vector2(-80f, 0f), GUIManager.Instance.AveriaSerif, 21, Color.white, true, Color.black, 150f, 35f, false);
		Text component = val3.GetComponent<Text>();
		if ((Object)(object)component != (Object)null)
		{
			m_inventoryAmountTexts[itemName] = component;
		}
	}

	private void CreateJobPanel()
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: 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_018a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0199: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_015f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Expected O, but got Unknown
		//IL_021a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0229: Unknown result type (might be due to invalid IL or missing references)
		//IL_0238: Unknown result type (might be due to invalid IL or missing references)
		//IL_0249: Unknown result type (might be due to invalid IL or missing references)
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0274: Unknown result type (might be due to invalid IL or missing references)
		//IL_027e: Expected O, but got Unknown
		//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0310: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f8: Expected O, but got Unknown
		//IL_03f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0403: Unknown result type (might be due to invalid IL or missing references)
		//IL_0412: Unknown result type (might be due to invalid IL or missing references)
		//IL_045b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0465: Expected O, but got Unknown
		m_jobPanel = GUIManager.Instance.CreateWoodpanel(GUIManager.CustomGUIFront.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, 0f), 600f, 700f, true);
		((Object)m_jobPanel).name = "GreydwarfJobPanel";
		GameObject val = GUIManager.Instance.CreateText("JOBS", m_jobPanel.transform, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, -45f), GUIManager.Instance.AveriaSerifBold, 30, GUIManager.Instance.ValheimOrange, true, Color.black, 400f, 45f, false);
		((Object)val).name = "GreydwarfJobTitle";
		GameObject val2 = GUIManager.Instance.CreateButton("X", m_jobPanel.transform, new Vector2(1f, 1f), new Vector2(1f, 1f), new Vector2(-35f, -35f), 50f, 50f);
		((Object)val2).name = "GreydwarfJobCloseButton";
		Button component = val2.GetComponent<Button>();
		if ((Object)(object)component != (Object)null)
		{
			((UnityEvent)component.onClick).AddListener(new UnityAction(CloseJobMenu));
		}
		GameObject val3 = GUIManager.Instance.CreateButton("Drop Inventory", m_inventoryPanel.transform, new Vector2(0.5f, 0f), new Vector2(0.5f, 0f), new Vector2(0f, 45f), 220f, 45f);
		((Object)val3).name = "GreydwarfDropInventoryButton";
		Button component2 = val3.GetComponent<Button>();
		if ((Object)(object)component2 != (Object)null)
		{
			((UnityEvent)component2.onClick).AddListener(new UnityAction(DropSelectedWorkerInventory));
		}
		m_jobStatusText = GUIManager.Instance.CreateText("Current Job: Inactive", m_jobPanel.transform, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, -90f), GUIManager.Instance.AveriaSerif, 20, Color.white, true, Color.black, 500f, 35f, false).GetComponent<Text>();
		m_jobList = new GameObject("GreydwarfJobList");
		m_jobList.transform.SetParent(m_jobPanel.transform, false);
		RectTransform val4 = m_jobList.AddComponent<RectTransform>();
		val4.anchorMin = new Vector2(0.5f, 0.5f);
		val4.anchorMax = new Vector2(0.5f, 0.5f);
		val4.pivot = new Vector2(0.5f, 0.5f);
		val4.anchoredPosition = new Vector2(0f, -50f);
		val4.sizeDelta = new Vector2(520f, 570f);
		string[] array = new string[6] { "Refuel Smelter", "Put Ore in Smelter", "Refuel Lightsources", "Refuel Charcoal Kiln", "Repair Structures", "Harvest Field" };
		WorkerJob[] array2 = new WorkerJob[6]
		{
			WorkerJob.RefuelSmelter,
			WorkerJob.PutOreInSmelter,
			WorkerJob.RefuelLightsources,
			WorkerJob.RefuelCharcoalKiln,
			WorkerJob.RepairStructures,
			WorkerJob.Harvest
		};
		float num = 496f;
		float num2 = num * 0.5f - 25f + 40f;
		CreateGatheringRow(num2);
		for (int i = 0; i < array.Length; i++)
		{
			CreateJobButton(array[i], array2[i], num2 - (float)(i + 1) * 62f);
		}
		CreatePlantingRow(num2 - 434f);
		GameObject val5 = GUIManager.Instance.CreateButton("Stop Working", m_jobPanel.transform, new Vector2(0.5f, 0f), new Vector2(0.5f, 0f), new Vector2(0f, 35f), 250f, 50f);
		((Object)val5).name = "GreydwarfStopWorkingButton";
		Button component3 = val5.GetComponent<Button>();
		if ((Object)(object)component3 != (Object)null)
		{
			((UnityEvent)component3.onClick).AddListener(new UnityAction(StopSelectedWorker));
		}
		m_jobPanel.SetActive(false);
	}

	private void UpdateGatherResourceButton()
	{
		if (!((Object)(object)m_gatherResourceText == (Object)null) && !((Object)(object)m_selectedWorker == (Object)null))
		{
			m_gatherResourceText.text = m_selectedWorker.GetCurrentResourceDefinition().DisplayName;
		}
	}

	private void PreviousSelectedWorkerResource()
	{
		if (!((Object)(object)m_selectedWorker == (Object)null))
		{
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.PreviousGatherResource);
			UpdateGatherResourceButton();
			RefreshJobStatus();
		}
	}

	private void NextSelectedWorkerResource()
	{
		if (!((Object)(object)m_selectedWorker == (Object)null))
		{
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.NextGatherResource);
			UpdateGatherResourceButton();
			RefreshJobStatus();
		}
	}

	private void UpdateFarmCropButton()
	{
		if (!((Object)(object)m_farmCropText == (Object)null) && !((Object)(object)m_selectedWorker == (Object)null))
		{
			m_farmCropText.text = m_selectedWorker.GetCurrentFarmCropDisplayName();
		}
	}

	private void PreviousSelectedFarmCrop()
	{
		if (!((Object)(object)m_selectedWorker == (Object)null) && !((Object)(object)m_plugin == (Object)null))
		{
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.PreviousFarmCrop);
		}
	}

	private void NextSelectedFarmCrop()
	{
		if (!((Object)(object)m_selectedWorker == (Object)null) && !((Object)(object)m_plugin == (Object)null))
		{
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.NextFarmCrop);
		}
	}

	private void DropSelectedWorkerInventory()
	{
		if (!((Object)(object)m_selectedWorker == (Object)null) && !((Object)(object)m_plugin == (Object)null))
		{
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.DropInventory);
		}
	}

	private void StopSelectedWorker()
	{
		if (!((Object)(object)m_selectedWorker == (Object)null) && !((Object)(object)m_plugin == (Object)null))
		{
			m_plugin.RequestWorkerCommand(m_selectedWorker, GreydwarfWorkersPlugin.WorkerCommand.StopWorking);
			RefreshJobStatus();
		}
	}

	private string GetCurrentJobText()
	{
		if ((Object)(object)m_selectedWorker == (Object)null)
		{
			return "Current Job: Inactive";
		}
		switch (m_selectedWorker.CurrentState)
		{
		case GreydwarfWorker.WorkerState.Gathering:
		case GreydwarfWorker.WorkerState.MovingToResource:
		case GreydwarfWorker.WorkerState.SearchingForChest:
		case GreydwarfWorker.WorkerState.MovingToChest:
		case GreydwarfWorker.WorkerState.WaitingForChest:
			return "Current Job: Gathering " + m_selectedWorker.GetCurrentResourceDefinition().DisplayName;
		case GreydwarfWorker.WorkerState.SearchingForSupplyChest:
		case GreydwarfWorker.WorkerState.MovingToSupplyChest:
		case GreydwarfWorker.WorkerState.RetrievingFromChest:
		case GreydwarfWorker.WorkerState.SearchingForSmelter:
		case GreydwarfWorker.WorkerState.MovingToSmelter:
		case GreydwarfWorker.WorkerState.DepositingToSmelter:
		case GreydwarfWorker.WorkerState.WaitingForSmelter:
			return "Current Job: Refuel Smelter";
		case GreydwarfWorker.WorkerState.SearchingForOreChest:
		case GreydwarfWorker.WorkerState.MovingToOreChest:
		case GreydwarfWorker.WorkerState.RetrievingOreFromChest:
		case GreydwarfWorker.WorkerState.SearchingForOreSmelter:
		case GreydwarfWorker.WorkerState.MovingToOreSmelter:
		case GreydwarfWorker.WorkerState.DepositingOreToSmelter:
		case GreydwarfWorker.WorkerState.WaitingForOreSmelter:
			return "Current Job: Put Ore in Smelter";
		case GreydwarfWorker.WorkerState.SearchingForFireplace:
		case GreydwarfWorker.WorkerState.MovingToFireplace:
		case GreydwarfWorker.WorkerState.SearchingForFireplaceFuel:
		case GreydwarfWorker.WorkerState.MovingToFireplaceFuelChest:
		case GreydwarfWorker.WorkerState.RetrievingFireplaceFuel:
		case GreydwarfWorker.WorkerState.MovingToFireplaceWithFuel:
		case GreydwarfWorker.WorkerState.DepositingToFireplace:
		case GreydwarfWorker.WorkerState.WaitingForFireplace:
			return "Current Job: Refuel Lightsources";
		case GreydwarfWorker.WorkerState.SearchingForKiln:
		case GreydwarfWorker.WorkerState.MovingToKiln:
		case GreydwarfWorker.WorkerState.DepositingToKiln:
		case GreydwarfWorker.WorkerState.WaitingForKiln:
		case GreydwarfWorker.WorkerState.SearchingForKilnChest:
		case GreydwarfWorker.WorkerState.MovingToKilnChest:
		case GreydwarfWorker.WorkerState.RetrievingKilnMaterial:
			return "Current Job: Refuel Charcoal Kiln";
		case GreydwarfWorker.WorkerState.SearchingForRepairTarget:
		case GreydwarfWorker.WorkerState.MovingToRepairTarget:
		case GreydwarfWorker.WorkerState.RepairingStructure:
		case GreydwarfWorker.WorkerState.WaitingForRepair:
			return "Current Job: Repair Structures";
		case GreydwarfWorker.WorkerState.SearchingForFarmField:
		case GreydwarfWorker.WorkerState.MovingToFarmField:
		case GreydwarfWorker.WorkerState.SearchingForFarmCrop:
		case GreydwarfWorker.WorkerState.MovingToFarmCrop:
		case GreydwarfWorker.WorkerState.HarvestingFarmCrop:
		case GreydwarfWorker.WorkerState.WaitingForFarmCrop:
		case GreydwarfWorker.WorkerState.SearchingForFarmDrop:
		case GreydwarfWorker.WorkerState.MovingToFarmDrop:
		case GreydwarfWorker.WorkerState.CollectingFarmDrop:
		case GreydwarfWorker.WorkerState.SearchingForFarmChest:
		case GreydwarfWorker.WorkerState.MovingToFarmChest:
		case GreydwarfWorker.WorkerState.WaitingForFarmChest:
			return "Current Job: Harvest Field";
		case GreydwarfWorker.WorkerState.SearchingForFarmSeedChest:
		case GreydwarfWorker.WorkerState.MovingToFarmSeedChest:
		case GreydwarfWorker.WorkerState.RetrievingFarmSeeds:
		case GreydwarfWorker.WorkerState.SearchingForFarmPlantPosition:
		case GreydwarfWorker.WorkerState.MovingToFarmPlantPosition:
		case GreydwarfWorker.WorkerState.PlantingFarmCrop:
		case GreydwarfWorker.WorkerState.WaitingForFarmPlant:
		case GreydwarfWorker.WorkerState.WaitingForFarmSeedChest:
		case GreydwarfWorker.WorkerState.MovingToFarmPlantField:
			return "Current Job: Plant Field";
		default:
			return "Current Job: Inactive";
		}
	}

	private void RefreshJobStatus()
	{
		if (!((Object)(object)m_jobStatusText == (Object)null))
		{
			m_jobStatusText.text = GetCurrentJobText();
		}
	}

	private void CreateJobButton(string jobName, WorkerJob job, float yPosition)
	{
		//IL_001c: 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)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Expected O, but got Unknown
		GameObject val = GUIManager.Instance.CreateButton(jobName, m_jobList.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, yPosition), 400f, 50f);
		((Object)val).name = "GreydwarfJobOption_" + job;
		Button component = val.GetComponent<Button>();
		if ((Object)(object)component != (Object)null)
		{
			WorkerJob selectedJob = job;
			((UnityEvent)component.onClick).AddListener((UnityAction)delegate
			{
				OnJobSelected(selectedJob);
			});
		}
	}

	private void CreateGatheringRow(float yPosition)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_0167: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Expected O, but got Unknown
		//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_023b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0245: Expected O, but got Unknown
		GameObject val = GUIManager.Instance.CreateButton("Gathering", m_jobList.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(-115f, yPosition), 220f, 50f);
		((Object)val).name = "GreydwarfGatheringButton";
		Button component = val.GetComponent<Button>();
		if ((Object)(object)component != (Object)null)
		{
			((UnityEvent)component.onClick).AddListener((UnityAction)delegate
			{
				OnJobSelected(WorkerJob.Gathering);
			});
		}
		GameObject val2 = GUIManager.Instance.CreateButton("<", m_jobList.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(40f, yPosition), 35f, 50f);
		((Object)val2).name = "GreydwarfGatherPreviousButton";
		Button component2 = val2.GetComponent<Button>();
		if ((Object)(object)component2 != (Object)null)
		{
			((UnityEvent)component2.onClick).AddListener(new UnityAction(PreviousSelectedWorkerResource));
		}
		GameObject val3 = GUIManager.Instance.CreateText("Wood", m_jobList.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(120f, yPosition - 3f), GUIManager.Instance.AveriaSerifBold, 21, Color.yellow, true, Color.black, 125f, 50f, false);
		((Object)val3).name = "GreydwarfGatherResourceText";
		m_gatherResourceText = val3.GetComponent<Text>();
		if ((Object)(object)m_gatherResourceText != (Object)null)
		{
			m_gatherResourceText.alignment = (TextAnchor)4;
		}
		GameObject val4 = GUIManager.Instance.CreateButton(">", m_jobList.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(200f, yPosition), 35f, 50f);
		((Object)val4).name = "GreydwarfGatherNextButton";
		Button component3 = val4.GetComponent<Button>();
		if ((Object)(object)component3 != (Object)null)
		{
			((UnityEvent)component3.onClick).AddListener(new UnityAction(NextSelectedWorkerResource));
		}
		UpdateGatherResourceButton();
	}

	private void CreatePlantingRow(float yPosition)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_0167: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Expected O, but got Unknown
		//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_023b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0245: Expected O, but got Unknown
		GameObject val = GUIManager.Instance.CreateButton("Plant", m_jobList.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(-115f, yPosition), 220f, 50f);
		((Object)val).name = "GreydwarfPlantButton";
		Button component = val.GetComponent<Button>();
		if ((Object)(object)component != (Object)null)
		{
			((UnityEvent)component.onClick).AddListener((UnityAction)delegate
			{
				OnJobSelected(WorkerJob.Plant);
			});
		}
		GameObject val2 = GUIManager.Instance.CreateButton("<", m_jobList.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(40f, yPosition), 35f, 50f);
		((Object)val2).name = "GreydwarfFarmCropPreviousButton";
		Button component2 = val2.GetComponent<Button>();
		if ((Object)(object)component2 != (Object)null)
		{
			((UnityEvent)component2.onClick).AddListener(new UnityAction(PreviousSelectedFarmCrop));
		}
		GameObject val3 = GUIManager.Instance.CreateText("Turnip", m_jobList.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(120f, yPosition - 3f), GUIManager.Instance.AveriaSerifBold, 21, Color.yellow, true, Color.black, 125f, 50f, false);
		((Object)val3).name = "GreydwarfFarmCropText";
		m_farmCropText = val3.GetComponent<Text>();
		if ((Object)(object)m_farmCropText != (Object)null)
		{
			m_farmCropText.alignment = (TextAnchor)4;
		}
		GameObject val4 = GUIManager.Instance.CreateButton(">", m_jobList.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(200f, yPosition), 35f, 50f);
		((Object)val4).name = "GreydwarfFarmCropNextButton";
		Button component3 = val4.GetComponent<Button>();
		if ((Object)(object)component3 != (Object)null)
		{
			((UnityEvent)component3.onClick).AddListener(new UnityAction(NextSelectedFarmCrop));
		}
		UpdateFarmCropButton();
	}

	private string GetDisplayItemName(string itemName)
	{
		if (string.IsNullOrEmpty(itemName))
		{
			return string.Empty;
		}
		if (Localization.instance != null)
		{
			string text = Localization.instance.Localize(itemName);
			if (!string.IsNullOrEmpty(text) && text != itemName)
			{
				return text;
			}
		}
		return itemName;
	}

	private void ClearWorkerList()
	{
		if (!((Object)(object)m_workerList == (Object)null))
		{
			m_workerStateTexts.Clear();
			for (int num = m_workerList.transform.childCount - 1; num >= 0; num--)
			{
				Object.Destroy((Object)(object)((Component)m_workerList.transform.GetChild(num)).gameObject);
			}
		}
	}

	private void ClearInventoryList()
	{
		m_inventoryAmountTexts.Clear();
		if (!((Object)(object)m_inventoryList == (Object)null))
		{
			for (int num = m_inventoryList.transform.childCount - 1; num >= 0; num--)
			{
				Object.Destroy((Object)(object)((Component)m_inventoryList.transform.GetChild(num)).gameObject);
			}
		}
	}

	private void CloseInventory()
	{
		if ((Object)(object)m_inventoryPanel != (Object)null)
		{
			m_inventoryPanel.SetActive(false);
		}
		m_selectedWorker = null;
		if ((Object)(object)m_panel != (Object)null)
		{
			m_panel.SetActive(true);
			RefreshWorkerList();
		}
	}

	private void OnDestroy()
	{
		if ((Object)(object)m_panel != (Object)null || (Object)(object)m_inventoryPanel != (Object)null)
		{
			IsOpen = false;
		}
	}

	private void UpdateWorkerListStatuses()
	{
		foreach (KeyValuePair<GreydwarfWorker, Text> workerStateText in m_workerStateTexts)
		{
			GreydwarfWorker key = workerStateText.Key;
			Text value = workerStateText.Value;
			if ((Object)(object)key == (Object)null || (Object)(object)value == (Object)null)
			{
				continue;
			}
			Character component = ((Component)key).GetComponent<Character>();
			if (key.IsWorking)
			{
				value.text = "Working";
				continue;
			}
			MonsterAI val = (((Object)(object)component != (Object)null) ? ((Component)component).GetComponent<MonsterAI>() : null);
			if ((Object)(object)val != (Object)null && (Object)(object)val.GetFollowTarget() != (Object)null)
			{
				value.text = "Following";
			}
			else
			{
				value.text = "Inactive";
			}
		}
	}

	private void UpdateInventoryAmounts()
	{
		if ((Object)(object)m_inventoryPanel == (Object)null || !m_inventoryPanel.activeSelf || (Object)(object)m_selectedWorker == (Object)null)
		{
			return;
		}
		WorkerInventory component = ((Component)m_selectedWorker).GetComponent<WorkerInventory>();
		if ((Object)(object)component == (Object)null)
		{
			return;
		}
		Dictionary<string, int> allItems = component.GetAllItems();
		foreach (KeyValuePair<string, Text> inventoryAmountText in m_inventoryAmountTexts)
		{
			string key = inventoryAmountText.Key;
			Text value = inventoryAmountText.Value;
			if (!((Object)(object)value == (Object)null))
			{
				int amount = component.GetAmount(key);
				int capacity = component.GetCapacity(key);
				value.text = amount + " / " + capacity;
			}
		}
		bool flag = allItems.Count != m_inventoryAmountTexts.Count;
		if (!flag)
		{
			foreach (string key2 in allItems.Keys)
			{
				if (!m_inventoryAmountTexts.ContainsKey(key2))
				{
					flag = true;
					break;
				}
			}
		}
		if (!flag)
		{
			foreach (string key3 in m_inventoryAmountTexts.Keys)
			{
				if (!allItems.ContainsKey(key3))
				{
					flag = true;
					break;
				}
			}
		}
		if (flag)
		{
			RefreshInventory();
		}
	}
}
[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
public static class MonsterAIWorkerPatch
{
	private static bool Prefix(MonsterAI __instance, float dt)
	{
		GreydwarfWorker component = ((Component)__instance).GetComponent<GreydwarfWorker>();
		if ((Object)(object)component == (Object)null)
		{
			return true;
		}
		if (!component.IsNetworkOwner)
		{
			return true;
		}
		if (!component.IsWorking)
		{
			return true;
		}
		return false;
	}
}
public class WorkerInventory : MonoBehaviour
{
	private Tameable m_tameable;

	private ZNetView m_nview;

	private const string InventoryZdoPrefix = "GreydwarfWorkers_Inventory_";

	private const string InventoryVersionZdoKey = "GreydwarfWorkers_InventoryVersion";

	private int m_lastKnownInventoryVersion = -1;

	private long m_lastKnownOwnerId = 0L;

	private bool m_networkStateInitialized = false;

	private readonly Dictionary<string, int> m_items = new Dictionary<string, int>();

	private static readonly Dictionary<string, string> ItemPrefabNames = new Dictionary<string, string>
	{
		{ "$item_wood", "Wood" },
		{ "$item_stone", "Stone" },
		{ "$item_coal", "Coal" },
		{ "$item_iron", "Iron" },
		{ "$item_copperore", "CopperOre" },
		{ "$item_tinore", "TinOre" },
		{ "$item_ironscrap", "IronScrap" },
		{ "$item_silverore", "SilverOre" },
		{ "$item_resin", "Resin" },
		{ "$item_greydwarf_eye", "GreydwarfEye" },
		{ "$item_guck", "Guck" },
		{ "$item_finewood", "FineWood" },
		{ "$item_roundlog", "RoundLog" },
		{ "$item_yggdrasilwood", "YggdrasilWood" },
		{ "$item_blackwood", "Blackwood" },
		{ "$item_frostwood", "Frostwood" },
		{ "$item_copper", "Copper" },
		{ "$item_tin", "Tin" },
		{ "$item_bronze", "Bronze" },
		{ "$item_silver", "Silver" },
		{ "$item_blackmetal", "BlackMetal" },
		{ "$item_flametal", "FlametalNew" },
		{ "$item_gold", "Gold" },
		{ "$item_blackmetalscrap", "BlackMetalScrap" },
		{ "$item_flametalore", "FlametalOre" },
		{ "$item_goldore", "GoldOre" }
	};

	public int CapacityPerResource => GreydwarfWorkersConfig.EffectiveDefaultResourceCapacity;

	private void Start()
	{
		m_nview = ((Component)this).GetComponent<ZNetView>();
		m_tameable = ((Component)this).GetComponent<Tameable>();
		EnsureFarmHarvestItemMappings();
		if (!((Object)(object)m_tameable == (Object)null) && m_tameable.IsTamed())
		{
			SyncFromNetwork(force: true);
		}
	}

	private void SyncFromNetwork(bool force)
	{
		if ((Object)(object)m_tameable == (Object)null || !m_tameable.IsTamed() || (Object)(object)m_nview == (Object)null || !m_nview.IsValid())
		{
			return;
		}
		ZDO zDO = m_nview.GetZDO();
		if (zDO != null)
		{
			long owner = zDO.GetOwner();
			int num = zDO.GetInt("GreydwarfWorkers_InventoryVersion", 0);
			bool flag = !m_networkStateInitialized || owner != m_lastKnownOwnerId;
			bool flag2 = num != m_lastKnownInventoryVersion;
			bool flag3 = m_nview.IsOwner();
			if (force || flag || flag2)
			{
				LoadInventory();
				m_lastKnownOwnerId = owner;
				m_lastKnownInventoryVersion = num;
				m_networkStateInitialized = true;
			}
			else if (flag3)
			{
			}
		}
	}

	private static void EnsureFarmHarvestItemMappings()
	{
		if ((Object)(object)ObjectDB.instance == (Object)null)
		{
			return;
		}
		foreach (FarmCropDefinition crop in FarmCropCatalog.Crops)
		{
			if (crop == null)
			{
				continue;
			}
			if (!string.IsNullOrEmpty(crop.HarvestItemName))
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(crop.HarvestItemName);
				if ((Object)(object)itemPrefab != (Object)null)
				{
					ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
					if ((Object)(object)component != (Object)null && component.m_itemData != null && component.m_itemData.m_shared != null)
					{
						string name = component.m_itemData.m_shared.m_name;
						if (!string.IsNullOrEmpty(name) && !ItemPrefabNames.ContainsKey(name))
						{
							ItemPrefabNames.Add(name, crop.HarvestItemName);
						}
					}
				}
			}
			if (string.IsNullOrEmpty(crop.PlantItemName))
			{
				continue;
			}
			GameObject itemPrefab2 = ObjectDB.instance.GetItemPrefab(crop.PlantItemName);
			if (!((Object)(object)itemPrefab2 != (Object)null))
			{
				continue;
			}
			ItemDrop component2 = itemPrefab2.GetComponent<ItemDrop>();
			if ((Object)(object)component2 != (Object)null && component2.m_itemData != null && component2.m_itemData.m_shared != null)
			{
				string name2 = component2.m_itemData.m_shared.m_name;
				if (!string.IsNullOrEmpty(name2) && !ItemPrefabNames.ContainsKey(name2))
				{
					ItemPrefabNames.Add(name2, crop.PlantItemName);
				}
			}
		}
	}

	private string GetInventoryZdoKey(string itemName)
	{
		return "GreydwarfWorkers_Inventory_" + itemName;
	}

	private void SaveInventory()
	{
		EnsureFarmHarvestItemMappings();
		if ((Object)(object)m_nview == (Object)null || !m_nview.IsValid() || !m_nview.IsOwner())
		{
			return;
		}
		ZDO zDO = m_nview.GetZDO();
		if (zDO == null)
		{
			return;
		}
		foreach (string key in ItemPrefabNames.Keys)
		{
			int amount = GetAmount(key);
			zDO.Set(GetInventoryZdoKey(key), amount);
		}
		int num = zDO.GetInt("GreydwarfWork