using UnityEngine;
using System.Collections;

public class PlayerHealthMobile : MonoBehaviour
{
    public int maxHealth = 100;
    public int currentHealth;

    public HealthBar healthBar;

    public SpriteRenderer graphics;

    public float invincibilityDelay = 0.2f;
    public float invincibilityTime = 2f;
    public bool isInvincible = false;

    public static PlayerHealthMobile instance;
    private void Awake()
    {
        if (instance != null)
        {
            Debug.LogWarning("plus d'une d'instance PlayerHealthMobile");
            return;
        }

        instance = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        currentHealth = maxHealth;
        healthBar.SetMaxHealth(maxHealth);
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.H)){
            TakeDamage(50);
        }
        
    }

    public void TakeDamage(int damage){
        if (!isInvincible)
        {
            currentHealth -= damage;
            healthBar.SetHealth(currentHealth);

            //v�rification si joueur est vivant
            if(currentHealth <= 0)
            {
                PlayerDie();
                return;
            }

            isInvincible = true;
            StartCoroutine(Invincibility());
            StartCoroutine(HandleInvincibilityDelay());
        }
        
    }

    public void PlayerDie()
    {
        //on ignore la collision entre un ennemi et le joueur quand il meurt 
        //cela permet de ne pas avoir le cadavre qui ce déplace à cause du box collider de l'ennemi
        //et cela permet aussi de ne pas avoir le joueur bloqué dans les airs s'il meurt en sautant sur l'ennemi
        Physics2D.IgnoreLayerCollision(6,7, true);
        MoveCharacterMobile.instance.enabled = false;
        MoveCharacterMobile.instance.rb.velocity = Vector3.zero;
        MoveCharacterMobile.instance.animator.SetBool("IsJumping", false);
        MoveCharacterMobile.instance.animator.SetTrigger("isDead");
        GameOverManager.instance.OnPlayerDeath();
             
    }

    public void Respawn()
    {
        Physics2D.IgnoreLayerCollision(6, 7, false);
        MoveCharacterMobile.instance.enabled = true;
        MoveCharacterMobile.instance.animator.SetTrigger("Respawn");
        currentHealth = maxHealth;
        healthBar.SetMaxHealth(maxHealth);
    }

    // affichage de l'invincibilit�, on clignote apr�s avoir perdu de la vie
    public IEnumerator Invincibility()
    {
        while (isInvincible)
        {
            graphics.color = new Color(1f, 1f, 1f, 0f);
            yield return new WaitForSeconds(invincibilityDelay);
            graphics.color = new Color(1f, 1f, 1f, 1f);
            yield return new WaitForSeconds(invincibilityDelay);
        }
    }

    public IEnumerator HandleInvincibilityDelay()
    {
        yield return new WaitForSeconds(invincibilityTime);
        isInvincible = false;
    }
   
}
