using System.Collections;
using UnityEngine;

public class GunLogic : MonoBehaviour
{

    [SerializeField] public GameObject lineRenderer;
    [SerializeField] public LayerMask layer;

    private GameObject Target;
    private bool isRotating;

    private float reloadtime = 1.0f;

    // Start is called before the first frame update
    void Start()
    {
        lineRenderer.SetActive(false);
    }

    // Update is called once per frame
    void Update()
    {

    }

    public IEnumerator SearchAndFire(GameObject target)
    {
        Target = target;
        float deltaAngle = 0;
        float damping = 0.995f;

        while (true)
        {
            Vector3 lookPos = Target.GetComponent<Transform>().position - transform.position;
            deltaAngle = Vector3.Angle(lookPos, transform.up);

            // rotate until reaching angle
            if (deltaAngle > 8)
            {
                isRotating = true;

                rotateGun(lookPos, damping);

                yield return null;
            }
            else
            {
                isRotating = false;

                shotGun();

                yield return new WaitForSeconds(reloadtime);
            }

        }
    }


    private void rotateGun(Vector3 lookPos, float damping)
    {
        lookPos.z = 0;
        Quaternion rotation = Quaternion.FromToRotation(Vector3.up, lookPos);

        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
    }

    private void shotGun()
    {
        // wystrzel pocisk

        RaycastHit2D hit = Physics2D.Raycast(
            transform.position,
            Target.GetComponent<Transform>().position,
            50.0f,
            layer
            );

        lineRenderer.GetComponent<LineRenderer>().SetPosition(0, transform.position);
        lineRenderer.GetComponent<LineRenderer>().SetPosition(1, hit.point);
        lineRenderer.SetActive(true);

        if (hit != null && hit.collider != null)
        {
            Target.GetComponent<DemonHeadMovement>().OverRideSpeed(1);
        }

    }

}
