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

public class Projectile : MonoBehaviour 
{
    public int Damage;
    public Entity Shooter; 
    public LayerMask InpenetretableMask;
    public LayerMask EntityLayerMask; 
    public float Seconds;

    private Vector3 startPos;
    private Vector3 endPos;
    private Vector3 rayDir; 
    private LineRenderer lineRenderer;

    private float secondsRemaining; 
    
    public void Start()
    {
        secondsRemaining = Seconds; 
        lineRenderer = GetComponent<LineRenderer>(); 
        startPos = this.transform.position; 
        RaycastHit2D[] hits = Physics2D.RaycastAll(this.transform.position, this.transform.right, 100.0f); 
        foreach(RaycastHit2D hit in hits)
        {
            if (Util.IsInLayerMask(hit.collider.gameObject.layer, EntityLayerMask))
            {
                Entity e = hit.collider.gameObject.GetComponent<Entity>(); 
                if(e && Shooter != e) 
                {
                    e.Harm(this.Damage, Shooter, startPos); 
                }
            }

            if(Util.IsInLayerMask(hit.collider.gameObject.layer, InpenetretableMask))
            {
                endPos = hit.point;
                break; 
            }
        }
        if(endPos == Vector3.zero)
        {
            endPos = this.transform.right * 100.0f; 
        }

        rayDir = (endPos - startPos).normalized;
        this.transform.position = Vector3.zero;

        lineRenderer.enabled = true; 
        lineRenderer.SetPosition(0, startPos);
        lineRenderer.SetPosition(1, endPos);

    }

    private void Update()
    {
        secondsRemaining -= Time.deltaTime;
        float fade = secondsRemaining / Seconds;
        Color c = lineRenderer.material.color;
        c.a = fade; 
        lineRenderer.material.color = c; 
        if (secondsRemaining <= 0) 
        {
            GameObject.Destroy(this.gameObject); 
        }
    }

}
