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

public class NetworkedAreaOfEffect : MonoBehaviour, IPunObservable
{
    [Header("Visuals:")]
    [SerializeField] protected GameObject telegraph;
    [SerializeField] protected GameObject effectVisual;
    [Header("Physics:")]
    [SerializeField] protected LayerMask abilityHitLayer;

    [Header("Set by Code")]
    public PhotonView photonView;
    public PhotonView owner;
    public Taggable ownerTag;
    public AreaOfEffectAbility ability;
    public float radius;
    public bool shouldResizeVisuals;
    public float telegraphDelay;
    public float lifeSpan;
    public bool canHitSelf;

    protected PhotonView possibleTarget;
    protected Taggable target;
    protected List<Taggable> targets = new List<Taggable>();

    protected Vector3 resizedByAbility = new Vector3();

    protected Collider[] hits;

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

    public virtual void Init()
    {
        if (photonView.IsMine)
        {
            if(shouldResizeVisuals)
            {
                resizedByAbility.x = radius * 2;
                resizedByAbility.z = radius * 2;

                telegraph.transform.localScale = resizedByAbility;
                effectVisual.transform.localScale = resizedByAbility;
            }

            photonView.RPC(nameof(RPC_RemoteInit), RpcTarget.Others, AbilityIndexer.Instance.Abilities.IndexOf(ability));

            StartCoroutine(ApplyTelegraphDelay(telegraphDelay));
        }
    }

    [PunRPC]
    protected virtual void RPC_RemoteInit(int abilityIndex)
    {
        ability = (AreaOfEffectAbility)AbilityIndexer.Instance.Abilities[abilityIndex];
    }

    protected virtual IEnumerator ApplyTelegraphDelay(float delay)
    {
        ShowTelegraph();

        yield return new WaitForSeconds(delay);

        ApplyArea();
    }

    protected virtual void ApplyArea()
    {
        ShowEffectVisual();

        CheckSurroundings();

        StartCoroutine(SelfDestruct());
    }


    protected virtual void CheckSurroundings()
    {
        hits = Physics.OverlapSphere(this.transform.position, radius, abilityHitLayer);
        targets.Clear();
        foreach (Collider collider in hits)
        {
            // Debug.Log("hit collider " + collider.name);

            possibleTarget = collider.GetComponentInParent<PhotonView>();
            if (possibleTarget != null)
                if (possibleTarget == owner && !canHitSelf) continue;

            target = collider.GetComponentInParent<Taggable>();

            //Debug.Log("hit collider, Got taggable: " + target.name);

            if (target == null) continue;

            //Debug.Log("hit collider, targetTag: " + target.targetTag.name);

            /*foreach (TargetTag tag in ability.targettingTags)
            {
                Debug.Log("hit collider, ability.Tags: " + tag);
            }*/
            if (!target.IsValidTarget(ability.targettingTags)) continue;

            Debug.Log("hit collider, added target: " + target.name);
            targets.Add(target);

        }

        foreach (BaseEffect effect in ability.abilityEffects)
        {
            effect.ApplyEffect(ownerTag, targets);
        }
    }

    protected void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(this.transform.position, radius);
    }

    protected IEnumerator SelfDestruct()
    {
        yield return new WaitForSeconds(lifeSpan);

        PhotonNetwork.Destroy(photonView);
    }

    protected void ShowTelegraph()
    {
        telegraph.SetActive(true);
        effectVisual.SetActive(false);
    }
    protected void ShowEffectVisual()
    {
        telegraph.SetActive(false);
        effectVisual.SetActive(true);
    }

    public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.IsWriting)
        {
            //stream.SendNext(telegraph.activeSelf);
            stream.SendNext(effectVisual.activeSelf);
        }
        if (stream.IsReading)
        {
            //telegraph.SetActive((bool)stream.ReceiveNext());
            effectVisual.SetActive((bool)stream.ReceiveNext());
        }
    }
}
