using UnityEngine;
using System.Collections;

[RequireComponent(typeof(CharacterController))]
public class PlayerStats : MonoBehaviour
{
    public float maxHealthPoints;

    public float HealthPoints
    {
        get;
        private set;
    }

    private void Start()
    {
        HealthPoints = maxHealthPoints;
    }

    private void OnControllerColliderHit(ControllerColliderHit hit)
    {
        if (hit.gameObject.tag == "DamageSource")
            StartCoroutine(ApplyDamage(hit.gameObject.GetComponent<DamageSource>()));
    }

    private IEnumerator ApplyDamage(DamageSource dmg)
    {
        int ticks = dmg.ticks;

        // safety
        if (!dmg.damageOverTime)
            ticks = 1;

        float secondsPerTick = dmg.duration / ticks;

        while (ticks-- > 0)
        {
            switch (dmg.damageType)
            {
                case DamageType.Flat:
                    HealthPoints -= dmg.damageValue;
                    break;
                case DamageType.PercentageMaximum:
                    HealthPoints -= maxHealthPoints * .01f * dmg.damageValue;
                    break;
                case DamageType.PercentageCurrent:
                    HealthPoints -= HealthPoints * .01f * dmg.damageValue;
                    break;
                case DamageType.PercentageMissing:
                    HealthPoints -= (maxHealthPoints - HealthPoints) * .01f * dmg.damageValue;
                    break;
                default:
                    break;
            }

            yield return new WaitForSeconds(secondsPerTick);
        }
    }
}
