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

public class BattleUI : BaseUI
{
	static BattleUI instance = null;
	public StarShip heroShip = null; // Set from editor or external
	public StarShip enemyShip = null; // Set from editor or external

	[SerializeField]Image heroHitPointsStripe = null;
	[SerializeField]Image enemyHitPointsStripe = null;
	[SerializeField]Text heroHitPointsCount = null;
	[SerializeField]Text enemyHitPointsCount = null;
	
	float currentHeroHitPoints = 0;
	float currentEnemyHitPoints = 0;

	// Weapon control
	[SerializeField]Button[] weaponButtons = null; // Set from editor
	[SerializeField]Image[] weaponTimers = null; // Set from editor

	public static void SetShip (StarShip heroShip, StarShip enemyShip)
	{
		if (instance != null)
		{
			instance.heroShip = heroShip;
			instance.enemyShip = enemyShip;
			instance.SetButtonState ();
		}
	}

	public void Fire(int weaponNum)
	{
		if (heroShip != null)
		{
			heroShip.Fire(weaponNum);
		}
	}

	protected override void Awake () {
		instance = this;
		base.Awake ();
	}

	void Start () {
		SetButtonState ();
	}

	void Update () {
		SetButtonState ();
		UpdateHitPoints ();
	}

	void UpdateHitPoints()
	{
		heroHitPointsCount.text = (heroShip.hitPoints > 0) ? heroShip.hitPoints.ToString () : "";
		enemyHitPointsCount.text = (enemyShip.hitPoints > 0) ? enemyShip.hitPoints.ToString () : "";
		float heroNormalizedLife = (float)heroShip.hitPoints / (float)heroShip.maxHitPoints;
		float enemyNormalizedLife = (float)enemyShip.hitPoints / (float)enemyShip.maxHitPoints;
		currentHeroHitPoints = currentHeroHitPoints * 0.9f + heroNormalizedLife * 0.1f;
		currentEnemyHitPoints = currentEnemyHitPoints * 0.9f + enemyNormalizedLife * 0.1f;
		heroHitPointsStripe.fillAmount = currentHeroHitPoints;
		enemyHitPointsStripe.fillAmount = currentEnemyHitPoints;
	}
	
	void SetButtonState ()
	{
		if (heroShip != null && heroShip.weapons != null)
		{
			if (weaponButtons != null)
			{
				for (int i = 0; i < weaponButtons.Length; i++)
				{
					if (weaponButtons[i] != null)
					{
						if (i < heroShip.weapons.Count)
						{
							if (heroShip.weapons[i] != null)
							{
								weaponButtons[i].interactable = heroShip.weapons[i].IsReady;
							}
						}
						else
						{
							weaponButtons[i].interactable = false;
						}
					}
				}
			}
			if (weaponTimers != null)
			{
				for (int i = 0; i < weaponTimers.Length; i++)
				{
					if (weaponTimers[i] != null)
					{
						if (i < heroShip.weapons.Count)
						{
							weaponTimers[i].enabled = true;
							weaponTimers[i].fillAmount = heroShip.weapons[i].ReloadTime;
						}
						else
						{
							weaponTimers[i].enabled = false;
						}
					}
				}
			}
		}
	}
}
