﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class HarvesterStats : MonoBehaviour
{
	[SerializeField] private Text costText;
	[SerializeField] private Text hpText;
	[SerializeField] private Text damageText;
	[SerializeField] private Text rangeText;

	private Attackable attackable;
	private Attack attack;
	private HarvestInfo harvestInfo;

	private void Start()
	{
		StartCoroutine(WaitForFence());
	}

	private IEnumerator WaitForFence()
	{
		while (GameManager.PlacementManager == null)
		{
			yield return null;
		}

		bool initialized = false;
		while (!initialized)
		{
			try
			{
				GameManager.PlacementManager.GetPlacementObject(PlaceableTypes.Harvester, true);
			}
			catch
			{
				initialized = false;
			}
			finally
			{
				initialized = true;
			}
			yield return null;
		}

		GameObject harvester = GameManager.PlacementManager.GetPlacementObject(PlaceableTypes.Harvester, true);
		attackable = harvester.GetComponent<Attackable>();
		attack = harvester.GetComponent<Attack>();
		harvestInfo = harvester.GetComponent<HarvestInfo>();

		if (attackable == null)
		{
			throw new System.Exception("Harvester has no Attackable");
		}

		if (harvestInfo == null)
		{
			throw new System.Exception("Harvester has no HarvestInfo");
		}
	}

	private void Update()
	{
		if (attackable == null || harvestInfo == null)
		{
			return;
		}

		costText.text = harvestInfo.GetCost().ToString();
		hpText.text = attackable.GetMaxHealth().ToString();
		damageText.text = attack.GetDamage().ToString();
		rangeText.text = attack.GetRadius().ToString();
	}
}
