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

public class LifeSystem : MonoBehaviour
{
    public int lifePoints = 3;
    public Animator anim;
    public bool colliding;
    public StateMachine sM;
    public GameObject[] hearts;
    public Material herosMat;
    public Shader shaderStd, shaderHit;
    public Renderer rend;
    // Start is called before the first frame update
    void OnEnable()
    {
        anim = GetComponentInChildren<Animator>();
        shaderStd = Shader.Find("Unlit/Texture");
        shaderHit= Shader.Find("Custom/Hit_fixed");
    }

    // Update is called once per frame
    void Update()
    {
        //if(anim.GetBool("Hurt"))
        //{
        //    anim.SetBool("Hurt", false);
        //}
    }

    public void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Enemy" && !colliding && lifePoints>0 && !sM.levelLost)
        {
            colliding =! colliding;
            StartCoroutine(TakingDamage());
        }

        if(lifePoints ==0)
        {
            Debug.Log("death");
            anim.SetBool("dead", true);
            sM.levelLost = true;
            lifePoints = -1;
        }
    }

    

    //private void OnCollisionEnter(Collision collision)
    //{
    //    if (collision.gameObject.tag == "Enemy")
    //    {
    //        if (lifePoints == 1)
    //        {
    //            anim.SetBool("Hurt", true);
    //            Debug.Log("death");
    //        }
    //        else
    //        {
    //            anim.SetBool("Hurt", true);
    //            lifePoints--;
    //            Debug.Log("hurt");
    //        }
    //    }
    //}

    IEnumerator TakingDamage()
    {
        anim.SetBool("walking", false);
        rend.material.shader = shaderHit;
        anim.SetBool("Hurt", true);
        lifePoints--;
        hearts[lifePoints].SetActive(false);
        yield return new WaitForSeconds(0.3f);
        anim.SetBool("Hurt", false);
        rend.material.shader = shaderStd;
        colliding = !colliding;
    }
}
