using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityStandardAssets.ImageEffects;

public class Player : MonoBehaviour {

    private bool hasArtefact = false;

    public float health = 100f;

    public GameObject effectsCamera;

    ColorCorrectionCurves curves;

    private float t = 0f;
    private float tMax = 1f;

    public float healTime = 2f;
    private float healStart = 0f;

    enum PlayerHealthState { none, damageWaiting, healing };
    PlayerHealthState healthState = PlayerHealthState.none;

	// Use this for initialization
	void Start () {
        Artefact.OnUse += AddArtefact;
        Altar.OnUse += RemoveArtefact;
        RoundManager.OnRoundStart += Restart;
        curves = effectsCamera.GetComponent<ColorCorrectionCurves>();
	}
	
	// Update is called once per frame
	void Update () {
        t += Time.deltaTime;
        if (healthState == PlayerHealthState.damageWaiting)
        {
            if (t >= tMax)
            {
                healthState = PlayerHealthState.healing;
                t = 0;
                tMax = healTime;
            }
        }
        else if(healthState == PlayerHealthState.healing)
        {
            if(t > tMax)
            {
                healthState = PlayerHealthState.none;
                t = 0;
            } else
            {
                health = QuadraticEasing(t, healStart, 100 - healStart, healTime);
            }
        }
        curves.saturation = Mathf.Clamp(health / 100, 0, 1);
	}

    public bool HasArtefact()
    {
        return hasArtefact;
    }

    public void AddArtefact()
    {
        hasArtefact = true;
    }

    public void RemoveArtefact()
    {
        hasArtefact = false;
    }

    public void TakeDamage(float damage)
    {
        health -= damage;
        if(health <= 0)
        {
            Die();
        }
        healthState = PlayerHealthState.damageWaiting;
        t = 0;
        tMax = healTime;
        healStart = health;
    }

    public void Die()
    {
        healthState = PlayerHealthState.none;
        SceneManager.LoadScene(0);
    }

    float QuadraticEasing(float t, float b, float c, float d)
    {
        t /= d / 2;
        if (t < 1) { return c / 2 * t * t + b; }
        t--;
        return -c / 2 * (t * (t - 2) - 1) + b;
    }

    void Restart()
    {
        health = 100f;
        t = 0;
        healthState = PlayerHealthState.none;
        hasArtefact = false;
    }
}
