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

public class HitpointKeeper : MonoBehaviour {
	public float hitpoints;
	public float maxHitpoints;
	private float lifePercent;
	private Text myHitpoints;
		
	public void Start () {
		myHitpoints = GetComponent<Text>();
		Reset(true);
	}
	
	public bool Damage(float points){
//		Debug.Log("HitpointKeeper.Damage: points "+points+". Hitpoints: "+hitpoints);
		hitpoints -= points;
		// prevent the overloaded damage mechanism from giving us health in excess of 100% with the following IF
		if (hitpoints > maxHitpoints) hitpoints = maxHitpoints;
		
//		Debug.Log("recalculated hitpoints: "+hitpoints);
		if (hitpoints > 0) {
			UpdateLifeAsPercent();
			return true;
		}
		UpdateLifeAsPercent();
		return false;
	}
	public void UpdateLifeAsPercent(){
		if (hitpoints > 0) {
			lifePercent = Mathf.Round((hitpoints / maxHitpoints)*100);
			myHitpoints.text = (lifePercent.ToString()+"%");
		} 
		else {
			lifePercent = 0;
			myHitpoints.text = (lifePercent.ToString()+"%");
		}
	}
	public void Reset(bool reset) {
		if (reset){
			hitpoints = maxHitpoints;
			UpdateLifeAsPercent();
			reset = false;
		}
	}
}