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

namespace StasisPod
{
  public class StasisPodScript : MonoBehaviour
  {
    public static event Action<object[]> SetRPC;
    private void Start()
    {
      id = "x" + (Math.Floor(transform.position.x) / 4).ToString() + "y" + (Math.Floor(transform.position.y) / 4).ToString();
      SetRPC += this.Set;
    }

    private void OnDestroy()
    {
      SetRPC -= this.Set;
    }

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

    internal void StartCallSet(bool inUse)
    {
      StartCoroutine(CallSet(inUse));
    }

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

    private void UpdateTile()
    {
      gameObject.transform.GetChild(1).gameObject.SetActive(inUse);
    }

    internal bool CanUse()
    {
      return !inUse;
    }

    public bool inUse = false;
    public string id;

    internal static void CallEventSetRPC(object[] args)
    {
      var setFrameItemRPC = StasisPodScript.SetRPC;
      if (setFrameItemRPC == null)
        return;
      setFrameItemRPC(args);
    }
  }
}