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

public class Projectile : MonoBehaviour
{

    [SerializeField]
    private Detection _detectionLinked;

    [SerializeField]
    private float _angle = 10f; //Default
    [SerializeField]
    private float _speed = 2f; //Default

    private Vector2 _vectorStart;
    private Vector2 _vectorEnd;
    
    private int _damage;
    private float _enemySpeed;
    private Entity _target;

    private Rigidbody2D _rigidbodyProjectile;
    private float _initialX;
    private float _initialY;
    private float _destinationX;
    private float _speedTime = 0f;

    private float _initialXDistance;

    private void Start() 
    {
        _rigidbodyProjectile = GetComponent<Rigidbody2D>();
        _initialX = transform.position.x;
        _initialY = transform.position.y;
        _destinationX = _vectorEnd.x - _initialX - _enemySpeed;
        
        _detectionLinked.gameObject.GetComponent<Detection>().EntityLinked = _target;
        _detectionLinked.gameObject.GetComponent<Detection>().ProjectileDamage = _damage;

        _initialXDistance = Mathf.Abs(_initialX - _destinationX);
    }

    private void Update()
    {
        float x = _speedTime;
        float y = (_angle*-Mathf.Pow(x, 2) + _destinationX * x); 

        transform.position = new Vector2(_initialX + x*_angle, _initialY + y);

        // Move projectile angle according to distance with target
        float lerpStep = (_destinationX - transform.position.x) / _initialXDistance;
        float angle = Mathf.Lerp(-100f, 45f, lerpStep);
        transform.eulerAngles = new Vector3(0, 0, angle);

        _speedTime += _speed * Time.deltaTime;

        if(y < 0) {
            Destroy(this.gameObject);
        }
    }

    //Getter and Setter
    public float EnemySpeed
    {
        get { return _enemySpeed; }
        set { _enemySpeed = value; }
    }

    public float Angle
    {
        get { return _angle; }
        set { _angle = value; }
    }

    public float Speed
    {
        get { return _speed; }
        set { _speed = value; }
    }

    public int Damage
    {
        get { return _damage; }
        set { _damage = value; }
    }

    public Vector2 VectorStart
    {
        get { return _vectorStart; }
        set { _vectorStart = value; }
    }

    public Vector2 VectorEnd
    {
        get { return _vectorEnd; }
        set { _vectorEnd = value; }
    }

    public Entity Target
    {
        get { return _target; }
        set { _target = value; }
    }
}
