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

public class NetworkedAreaOfEffectOverTime : NetworkedAreaOfEffect
{
    public float duration;
    public bool followUser;


    private float endTime;

    public override void Init()
    {
        if (photonView.IsMine)
        {
            //resizedByAbility.x = radius * 2;
            //resizedByAbility.y = 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));

            ApplyArea();

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

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

        effectVisual.SetActive(false);
    }

    [PunRPC]
    protected override void RPC_RemoteInit(int abilityIndex)
    {
        ability = (AreaOfEffectOverTimeAbility)AbilityIndexer.Instance.Abilities[abilityIndex]; // TODO: change casting to areaofeffectovertimeability
    }

    protected override IEnumerator ApplyTelegraphDelay(float delay)
    {
        return base.ApplyTelegraphDelay(delay);
    }

    protected override void ApplyArea()
    {
        effectVisual.SetActive(true);

        StartCoroutine(ApplyAreaOverTime());
    }

    private IEnumerator ApplyAreaOverTime()
    {
        endTime = Time.time + duration;
        while (Time.time < endTime)
        {
            yield return new WaitForSeconds(0.5f);
            CheckSurroundings();
        }

        StartCoroutine(SelfDestruct());
    }

    protected override void CheckSurroundings()
    {
        base.CheckSurroundings(); //TODO: spread the total value over ticks, for now just apply the instant effect every tick, manage tick values on effect applied
    }
}
