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

public class NetworkedAntiProjectile : MonoBehaviour
{
    [Header("Visuals")]
    [SerializeField] private GameObject visuals;

    [Header("Hit Filtering Tag")]
    [SerializeField] private Taggable antiProjectileTag;

    [Header("Set by code")]
    public PhotonView photonView;
    public PhotonView owner;
    public Taggable ownerTag;
    public AntiProjectileAbility ability;
    public float duration;
    public bool followUser;

    private bool waitingForDestroy = false;

    private float endTime;

    public UnityEvent onProjectileBlocked = new UnityEvent();

    private void Awake()
    {
        photonView = GetComponent<PhotonView>();
        antiProjectileTag = GetComponent<Taggable>();
    }

    public void Init()
    {
        waitingForDestroy = false;

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

            StartCoroutine(SelfDestruct());

            if (followUser)
                StartCoroutine(FollowUser());
        }
    }

    IEnumerator FollowUser()
    {
        endTime = Time.time + duration;
        while (Time.time < endTime)
        {
            this.transform.position = owner.transform.position;
            yield return new WaitForEndOfFrame();
        }

        visuals.SetActive(false);
    }

    [PunRPC]
    private void RPC_RemoteInit(int abilityIndex)
    {
        ability = (AntiProjectileAbility)AbilityIndexer.Instance.Abilities[abilityIndex];
    }

    [PunRPC]
    private void RPC_DisableVisuals()
    {
        visuals.SetActive(false);
    }

    public void SendBlockNotice()
    {
        if (waitingForDestroy) return;

        photonView.RPC(nameof(RPC_SendBlockNotice), RpcTarget.All);
    }

    [PunRPC]
    private void RPC_SendBlockNotice()
    {
        waitingForDestroy = true;

        if (!photonView.IsMine)
        {
            visuals.SetActive(false);
            return;
        }

        StartCoroutine(DelayedDestroy());
    }

    IEnumerator DelayedDestroy()
    {
        visuals.SetActive(false);

        photonView.RPC(nameof(RPC_DisableVisuals), RpcTarget.Others);

        yield return new WaitForSeconds(1f);

        PhotonNetwork.Destroy(photonView);
    }

    IEnumerator SelfDestruct()
    {
        yield return new WaitForSeconds(duration);

        waitingForDestroy = true;

        StartCoroutine(DelayedDestroy());
    }
}
