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

public class InvincibleOnDamage : MonoBehaviour
{
    SpriteRenderer playerSR;
    Color normalColor = new Color(71f/ 255f, 71f / 255f, 71f / 255f, 1f);
    Color flashColor = new Color(200f / 255f, 200f / 255f, 56f / 255f, 0.25f);
    // Start is called before the first frame update
    void Start()
    {
        playerSR = GetComponent<SpriteRenderer>();
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Hazard")
        {
            if (PlayerData.instance.IsInvincible())
            {
                return;
            }
            StartCoroutine(goInvincible(0.3f));
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Hazard")
        {
            if (PlayerData.instance.IsInvincible())
            {
                return;
            }
            StartCoroutine(goInvincible(0.3f));
        }
    }

    private IEnumerator goInvincible(float flashDuration)
    {
        float duration = 0f;
        PlayerData.instance.SetInvincible(true);
        while (duration < flashDuration)
        {
            if (playerSR.color == normalColor)
            {
                playerSR.color = flashColor;
            } else
            {
                playerSR.color = normalColor;
            }
            duration += Time.deltaTime;
            yield return new WaitForSeconds(0.1f);
        }
        playerSR.color = normalColor;
        PlayerData.instance.SetInvincible(false);

    }
}
