using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HealthBar : MonoBehaviour {

	public static HealthBar instance = null;

	[SerializeField] Sprite healthGold;
	[SerializeField] Sprite healthSilver;
	[SerializeField] Sprite healthBronze;

	private List<Transform> healths = new List<Transform>();

	void Awake() {
        if (instance == null) {
            instance = this;
        } else if (instance != this) {
            Destroy(gameObject);
        }

		for (int i = 0; i < transform.childCount; i += 1) {
			healths.Add(transform.GetChild(i).transform);
		}
	}

	public void UpdateHealth(float maxHealth, float health) {
		float bar = Mathf.Ceil(health / 3) - 1;
		float remainder = health % 3;
		
		for (int i = 0; i < healths.Count; i += 1) {
			Transform h = healths[i];
			if (i < bar) {
				h.GetComponent<SpriteRenderer>().sprite = healthGold;
				h.gameObject.SetActive(true);
			} else if (i == bar) {
				if (remainder == 2) {
					h.GetComponent<SpriteRenderer>().sprite = healthSilver;
				} else if (remainder == 1) {
					h.GetComponent<SpriteRenderer>().sprite = healthBronze;
				} else if (remainder == 0) {
					h.GetComponent<SpriteRenderer>().sprite = healthGold;
				}
				h.gameObject.SetActive(true);
			} else {
				h.gameObject.SetActive(false);
			}
		}

		if (health == 45) {
			GameManager.instance.Win();
		}
	}
}
