
using GadgetCore.API;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace StasisPod
{
  public class StasisPodScript : MonoBehaviour
  {
    public static List<StasisPodScript> StasisPods = new List<StasisPodScript>();

    public bool inUse = false;
    public string id;

    private void Start()
    {
      id = "x" + (Math.Floor(transform.position.x) / 4).ToString() + "y" + (Math.Floor(transform.position.y) / 4).ToString();
      StasisPods.Add(this);
    }

    private void OnDestroy()
    {
      StasisPods.Remove(this);
    }

    internal void UpdateInUse(bool inUse) => StartCoroutine(UpdateInUseInternal(inUse));

    private IEnumerator UpdateInUseInternal(bool inUse)
    {
      yield return new WaitForSeconds(0.01f);
      GadgetCoreAPI.CallCustomRPC(StasisPod.RPCSetPodInUse, RPCMode.AllBuffered, new object[] { this.id, inUse });
      yield break;
    }

    internal static void CallEventSetRPC(object[] args)
    {
      foreach (var pod in StasisPods)
      {
        pod.UpdateInUseFromRPC(args);
      }
    }

    private void UpdateInUseFromRPC(object[] o)
    {
      if (o[0].ToString() == id)
      {
        inUse = (bool)o[1];
        UpdateTile();
      }
    }

    private void UpdateTile() => gameObject.transform.GetChild(1).gameObject.SetActive(inUse);

    internal bool CanUse() => !inUse;
  }
}