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

public class EnemyProjectileBehaviour : MonoBehaviour
{

    private float speed = 800f;
    private Rigidbody2D rb;
    private Vector2 velocity = Vector2.zero;
    private float despawnTime = 3f;
    private SpriteRenderer spriteRenderer;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        spriteRenderer = GetComponent<SpriteRenderer>();
    }

    // Update is called once per frame
    void Update()
    {
        rb.velocity = velocity;
        if (velocity.x > 0)
        {
            spriteRenderer.flipX = false;
        }
        else
        {
            spriteRenderer.flipX = true;
        }
    }

    private IEnumerator Despawn()
    {
        var t = despawnTime;
        while (t > 0)
        {
            t -= Time.deltaTime;
            yield return null;
        }
        Destroy(gameObject);
        yield return null;
    }

    public void Shoot(Vector3 origin, Vector3 target)
    {
        transform.position = origin;
        velocity = (target - origin).normalized * speed;
        StartCoroutine(Despawn());
    }


    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Player")
        {
            if (!collision.GetComponent<MovementManager>().IsHiding)
            {
                SceneManager.LoadScene("Menu");
            }

        }
       
        if (collision.tag == "OnShell" || collision.tag == "Environment")
        {
            Destroy(gameObject);
        }
        else if (collision.tag == "Shell" && !collision.isTrigger)
        {
            Destroy(gameObject);
        }
    }
}
