﻿using System;
using UnityEngine;

namespace AC
{

	public class StatCalculator : MonoBehaviour
	{

		#region Variables

		[SerializeField] private Container[] containers = new Container[0];
		[SerializeField] private Stat[] stats = new Stat[0];

		#endregion


		#region UnityStandards

		private void OnEnable ()
		{
			EventManager.OnContainerAdd += OnContainerAdd;
			EventManager.OnContainerRemove += OnContainerRemove;
			EventManager.OnMenuTurnOn += OnMenuTurnOn;
			EventManager.OnInitialiseScene += OnInitialiseScene;
			EventManager.OnVariableChange += OnVariableChange;

			UpdateStats ();
		}


		private void OnDisable ()
		{
			EventManager.OnContainerAdd -= OnContainerAdd;
			EventManager.OnContainerRemove -= OnContainerRemove;
			EventManager.OnMenuTurnOn -= OnMenuTurnOn;
			EventManager.OnInitialiseScene -= OnInitialiseScene;
			EventManager.OnVariableChange -= OnVariableChange;
		}

		#endregion


		#region CustomEvents

		private void OnContainerAdd (Container container, InvInstance containerItem)
		{
			UpdateStats ();
		}


		private void OnContainerRemove (Container container, InvInstance containerItem)
		{
			UpdateStats ();
		}


		private void OnMenuTurnOn (Menu menu, bool isInstant)
		{
			UpdateStats ();
		}


		private void OnInitialiseScene ()
		{
			UpdateStats ();
		}


		private void OnVariableChange (GVar variable)
		{
			foreach (Stat stat in stats)
			{
				if (!string.IsNullOrEmpty (stat.offsetterVariable) && stat.offsetterVariable == variable.label)
				{
					stat.UpdateVariable (containers);
				}
			}
		}

		#endregion


		#region PrivateFunctions

		private void UpdateStats ()
		{
			if (!KickStarter.kickStarter.HasInitialisedAC) return;
			
			foreach (Stat stat in stats)
			{
				stat.UpdateVariable (containers);
			}
		}


		#endregion


		#region PrivateClasses

		[Serializable]
		private class Stat
		{

			public string property;
			public string baseVariable;
			public string offsetterVariable;


			public void UpdateVariable (Container[] containers)
			{
				if (string.IsNullOrEmpty (baseVariable)) return;

				int defaultValue = KickStarter.variablesManager.GetVariable (baseVariable).IntegerValue;
				int totalValue = defaultValue;

				if (!string.IsNullOrEmpty (offsetterVariable))
				{
					int offsetValue = GlobalVariables.GetVariable (offsetterVariable).IntegerValue;
					totalValue += offsetValue;
				}

				if (!string.IsNullOrEmpty (property))
				{
					foreach (Container container in containers)
					{
						if (container.InvCollection.InvItems.Count == 0 || container.InvCollection.InvItems[0] == null)
						{
							continue;
						}

						if (InvInstance.IsValid (container.InvCollection.GetInstanceAtIndex (0)))
						{
							int statValue = container.InvCollection.GetInstanceAtIndex (0).GetProperty (property).IntegerValue;
							totalValue += statValue;
						}
					}
				}

				GlobalVariables.GetVariable (baseVariable).IntegerValue = totalValue;
			}

		}

		#endregion

	}

}