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

public class DamageItem : MonoBehaviour
{
    public bool canMakeDamages = false;
    private float timeToBlink = 1f;
    private SpriteRenderer sr;
    public int damage;

    // Start is called before the first frame update
    void Start()
    {
        canMakeDamages = false;
        sr = GetComponent<SpriteRenderer>();
        Invoke("SetMakeDamages", timeToBlink);
        StartCoroutine(Blink(timeToBlink));

    }

    public void SetMakeDamages()
    {
        canMakeDamages = true;
    }


    public IEnumerator Blink(float timer)
    {

        //canMove = false;
        while (timer > 0f)
        {
            sr.enabled = !sr.enabled;
            timer -= Time.deltaTime;

            yield return new WaitForFixedUpdate();
        }

        sr.enabled = true;
        //canMove = true;
        yield return null;
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.tag == "Player" && canMakeDamages)
        {
            collision.gameObject.GetComponent<PlayerController>().TakeDamage(damage);
            canMakeDamages = false;
            StartCoroutine(Blink(timeToBlink));
            Invoke("DestroyItem", 1f);
        }
    }

    public void DestroyItem()
    {
        Destroy(gameObject);

    }
}
