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

public class FenceStats : MonoBehaviour
{
	[SerializeField] private Text costText;
	[SerializeField] private Text hpText;
	[SerializeField] private Text rotationText;

	private Attackable attackable;
	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.Fence, true);
			}
			catch
			{
				initialized = false;
			}
			finally
			{
				initialized = true;
			}
			yield return null;
		}

		GameObject fence = GameManager.PlacementManager.GetPlacementObject(PlaceableTypes.Fence, true);
		attackable = fence.GetComponent<Attackable>();
		harvestInfo = fence.GetComponent<HarvestInfo>();

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

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

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

		costText.text = harvestInfo.GetCost().ToString();
		hpText.text = attackable.GetMaxHealth().ToString();
		rotationText.text = GameManager.PlacementManager.placementRotation + "°";
	}
}
