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

public class NPCSightControllerBase : MonoBehaviour
{
    [Header("Settings:")]
    [SerializeField] protected float sightRange;

    protected SphereCollider sight;

    protected PhotonView photonView;
    protected PhotonView otherView;

    protected Taggable myTag;
    protected Taggable possibleTarget;

    protected NPCControllerBase npcController;

    private void Awake()
    {
        npcController = GetComponentInParent<NPCControllerBase>();
        myTag = GetComponentInParent<Taggable>();
        photonView = GetComponentInParent<PhotonView>();
    }

    protected void Start()
    {
        if (!photonView.IsMine) return;

        sight = this.gameObject.AddComponent<SphereCollider>();
        sight.radius = sightRange;
        sight.isTrigger = true;
    }

    protected virtual void OnTriggerEnter(Collider other)
    {
        if (!photonView.IsMine) return;

        otherView = other.GetComponentInParent<PhotonView>();
        if (otherView != null)
        {
            if (otherView == photonView) return;
        }

        possibleTarget = other.GetComponentInParent<Taggable>();

        if (possibleTarget == null) return;

        if (possibleTarget.targetTag == myTag.targetTag || myTag.targetTag.AlliedTags.Contains(possibleTarget.targetTag)) return;

        if (npcController.possibleTargets.Contains(possibleTarget)) return;

        npcController.possibleTargets.Add(possibleTarget);

        npcController.onPossibleTargetEnteredSight.Invoke();
    }

    protected virtual void OnTriggerExit(Collider other)
    {
        if (!photonView.IsMine) return;

        otherView = other.GetComponentInParent<PhotonView>();
        if (otherView != null)
        {
            if (otherView == photonView) return;
        }

        possibleTarget = other.GetComponentInParent<Taggable>();

        if (possibleTarget == null) return;

        if (possibleTarget.targetTag == myTag.targetTag) return;

        if (!npcController.possibleTargets.Contains(possibleTarget)) return;

        npcController.possibleTargets.Remove(possibleTarget);

        npcController.onPossibleTargetExitedSight.Invoke();
    }


    protected virtual void OnDrawGizmosSelected()
    {
        Gizmos.DrawWireSphere(this.transform.position, sightRange);
    }
}
