using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ProjectileSpawnLocationController : MonoBehaviour
{
    [SerializeField] protected Transform lookAt;
    Plane plane = new Plane(Vector3.down, 0);

    protected PhotonView photonView;

    Ray ray;

    protected Vector3 targetPoint = new Vector3();

    bool isCasting;
    Vector3 castLookatSnapshot;

    protected virtual void Awake()
    {
        photonView = GetComponentInParent<PhotonView>();
    }

    private void OnEnable()
    {
        CastBarHandler.Instance.OnCastingStateChanged.AddListener(UpdateIsCastingState);
    }
    private void OnDisable()
    {
        CastBarHandler.Instance.OnCastingStateChanged.RemoveListener(UpdateIsCastingState);
    }

    // Start is called before the first frame update
    protected virtual void Start()
    {
        if (!photonView.IsMine) this.enabled = false;
    }

    // Update is called once per frame
    protected virtual void Update()
    {
        if (Camera.main == null) return;

        if (isCasting)
        {
            lookAt.forward = castLookatSnapshot;
            return;
        }
        

        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (plane.Raycast(ray, out float distance))
        {
            targetPoint = ray.GetPoint(distance);
            targetPoint.y = this.transform.position.y;
            lookAt.forward = targetPoint - lookAt.position;
        }
    }

    public Vector3 GetLookat()
    {
        return lookAt.forward;
    }

    private void UpdateIsCastingState(bool isCasting)
    {
        this.isCasting = isCasting;

        if(isCasting)
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (plane.Raycast(ray, out float distance))
            {
                targetPoint = ray.GetPoint(distance);
                targetPoint.y = this.transform.position.y;
                lookAt.forward = targetPoint - lookAt.position;
                castLookatSnapshot = lookAt.forward;
            }
        }
    }
}
