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

public class LaserScript : MonoBehaviour {

    float start;

    private void Start()
    {
        start = Time.time;
    }

    void Update()
    {
        Vector3 a = GetComponent<LineRenderer>().GetPosition(0);
        Vector3 b = GetComponent<LineRenderer>().GetPosition(1);
        RaycastHit2D[] rh =
            Physics2D.RaycastAll(a, (b - a).normalized, 150, ~(LayerMask.GetMask("player") | (2 << Physics2D.IgnoreRaycastLayer)));
        //print(rh.Length);
        //print(rh.Length);
        foreach (RaycastHit2D r in rh)
        {
            try
            {
                //print(r.rigidbody.gameObject.name);
            }catch(System.Exception e)
            {

            }
            if (r.rigidbody == null) continue;
            if (r.rigidbody.gameObject == null) continue;
            //print ("taking");
            r.rigidbody.gameObject.SendMessage("TakeDamage", 20, SendMessageOptions.DontRequireReceiver);
            r.rigidbody.gameObject.SendMessage("TakeHit", (b - a).normalized*4, SendMessageOptions.DontRequireReceiver);

            r.rigidbody.gameObject.SendMessage("Act", "Laser", SendMessageOptions.DontRequireReceiver);

            // tried to use sendmessages but they suck
            HealthScript h = r.rigidbody.gameObject.GetComponent<HealthScript>();
            if (h!= null)
            {
                if (h.health <= 0)
                {
                    GameObject.Find("player").GetComponent<PlayerScript>().IKilled(r.rigidbody.gameObject);
                }
            }
        }

    }

    private void FixedUpdate()
    {
        GetComponent<LineRenderer>().startWidth = 0.2f + Mathf.Min(0.2f, Time.time - start) * 2;
        GetComponent<LineRenderer>().endWidth = 0.5f + Mathf.Min(0.2f, Time.time - start) * 5;
    }

    /*private void OnTriggerStay2D(Collider2D coll)
    {
        coll.gameObject.SendMessage("TakeDamage", 10, SendMessageOptions.DontRequireReceiver);
        coll.gameObject.SendMessage("TakeHit", (coll.transform.position - transform.position).normalized*100, SendMessageOptions.DontRequireReceiver);
        //GameObject.Destroy(gameObject, 0.01f);
    }*/
}



