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

public class Projectile : MonoBehaviour 
{
    [Header("General")]
	[SerializeField] private bool playerOwned;
	[SerializeField] private bool hittable;
	[SerializeField] private bool followPlayer;
	public float followSpeed;
	public int damage;

    [Header("Other")]
	public Rigidbody2D rig;
	private GameObject player;
	[SerializeField] private GameObject projectileDeathParticle;

	void Start ()
	{
        if (!followPlayer)
        {
            Destroy(gameObject, 3.0f);
        }
        else
        {
            Destroy(gameObject, 10.0f);
        }

        if (GetComponent<TrailRenderer>())
        {
            GetComponent<TrailRenderer>().sortingLayerName = "Enemy";
        }
	}

	void Update ()
	{
		// Преследование игрока
		if(followPlayer)
		{
			if(!player)
			{
				if(Game.game.player)
				{
					player = Game.game.player.gameObject;
				}
			}
			else
			{
				transform.position = Vector3.MoveTowards(transform.position, player.transform.position, followSpeed * Time.deltaTime);
			}
		}
	}

	void OnTriggerEnter2D (Collider2D col)
	{
		//Ранение врагов
		if(playerOwned)
		{
			if(col.gameObject.tag == "Enemy")
			{
                col.gameObject.GetComponent<Enemy>().TakeDamage(damage);

                Destroy(gameObject);
			}
			//Уничтожение снарядов врагов
			else if(col.gameObject.tag == "Projectile")
			{
				if(col.gameObject.GetComponent<Projectile>().hittable)
				{
					Destroy(col.gameObject);
					GameObject pe = Instantiate(projectileDeathParticle, col.gameObject.transform.position, Quaternion.identity);
					Destroy(pe, 1);
					Destroy(gameObject);
				}
			}
		}
		//Ранение игрока
		else
		{
			if(col.gameObject.tag == "Player")
			{
				Game.game.player.TakeDamage(damage);
				Destroy(gameObject);
			}
		}
	}
}
