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

namespace ScrapYard
{
  public class ScrapYardShopStandScript : MonoBehaviour
  {
    public static readonly FieldInfo inventoryField = typeof(GameScript).GetField("inventory", BindingFlags.NonPublic | BindingFlags.Instance);

    private void Awake()
    {
      UpdateUI();
    }

    [RPC]
    private void Set(int itemID, int price, int quantity, int currencyItemID)
    {
      this.itemID = ItemRegistry.Singleton.ConvertIDToLocal(itemID);
      this.currencyItemID = ItemRegistry.Singleton.ConvertIDToLocal(currencyItemID);
      this.price = price;
      this.quantity = quantity;
      UpdateUI();
    }

    internal void StartCallSet(int itemID, int price, int quantity, int currencyItemID)
    {
      StartCoroutine(CallSet(itemID, price, quantity, currencyItemID));
    }

    private IEnumerator CallSet(int itemID, int price, int quantity, int currencyItemID)
    {
      yield return new WaitForSeconds(0.1f);
      itemID = ItemRegistry.Singleton.ConvertIDToHost(itemID);
      currencyItemID = ItemRegistry.Singleton.ConvertIDToHost(currencyItemID);
      gameObject.GetComponent<NetworkView>().RPC("Set", RPCMode.AllBuffered, new object[] { itemID, price, quantity, currencyItemID });
      yield break;
    }

    private void UpdateUI()
    {
      gameObject.transform.GetChild(1).GetComponent<Animation>().Play("animationStand");
      gameObject.transform.GetChild(1).GetComponent<Renderer>().material = (Material)Resources.Load("i/i" + itemID);
      gameObject.transform.GetChild(2).GetChild(1).GetComponent<Renderer>().material = (Material)Resources.Load("i/i" + currencyItemID);

      ItemInfo info = ItemRegistry.GetItem(itemID);

      string title = (quantity > 1 ? quantity + "x " : "") + info.Name;

      gameObject.transform.GetChild(2).GetChild(0).GetComponent<TextMesh>().text = title;
      gameObject.transform.GetChild(2).GetChild(0).GetChild(0).GetComponent<TextMesh>().text = title;
      gameObject.transform.GetChild(2).GetChild(2).GetComponent<TextMesh>().text = "" + price;
      gameObject.transform.GetChild(2).GetChild(2).GetChild(0).GetComponent<TextMesh>().text = "" + price;
    }

    private void OnTriggerEnter(Collider c)
    {
      if (c.gameObject.layer == 8)
      {
        gameObject.transform.GetChild(2).gameObject.SetActive(true);
      }
    }

    private void OnTriggerExit(Collider c)
    {
      if (c.gameObject.layer == 8)
      {
        gameObject.transform.GetChild(2).gameObject.SetActive(false);
      }
    }

    private int GetItemAmount(GameScript gameScript, int id)
    {
      int num = 0;
      Item[] inventory = (Item[])inventoryField.GetValue(gameScript);
      for (int i = 0; i < 45; i++)
      {
        if (inventory[i].id == id)
        {
          num += inventory[i].q;
        }
      }
      return num;
    }

    private void RemoveItemAmount(GameScript gameScript, int id, int amount)
    {
      Item[] inventory = (Item[])inventoryField.GetValue(gameScript);
      for (int i = 0; i < 45; i++)
      {
        if (inventory[i].id == id)
        {
          if (amount - inventory[i].q > 0)
          {
            amount -= inventory[i].q;
            inventory[i] = gameScript.EmptyItem();
            gameScript.RefreshSlot(i);
          }
          else
          {
            if (amount - inventory[i].q == 0)
            {
              inventory[i] = gameScript.EmptyItem();
              gameScript.RefreshSlot(i);
              break;
            }
            inventory[i].q -= amount;
            gameScript.RefreshSlot(i);
            break;
          }
        }
      }
    }

    private void Request()
    {
      Core.logger.Log("Requesting Item in Stand");
      var gameScript = (GameScript)Camera.main.GetComponent("GameScript");
      int num = GetItemAmount(gameScript, currencyItemID);


      Core.logger.Log("Got a Price for the Stand: " + num);

      if (num >= price)
      {
        base.GetComponent<AudioSource>().PlayOneShot((AudioClip)Resources.Load("Au/purchase"), Menuu.soundLevel / 10f);
        RemoveItemAmount(gameScript, currencyItemID, price);
        Item item = new Item(itemID, quantity, 0, 0, 0, new int[3], new int[3]);
        Core.logger.Log("Spawn item");
        GadgetCoreAPI.SpawnItem(base.transform.position, item);
      }
      else if (itemID != 0)
      {
        ItemRegistry.GetItem(itemID);
        GameObject gameObject = (GameObject)Object.Instantiate(Resources.Load("txtError"), MenuScript.player.transform.position, Quaternion.identity);
        gameObject.SendMessage("InitError", "Insufficient Currency!");
      }
      Core.logger.Log("End Shop request");
    }

    public int itemID = 1;
    public int price = 1;
    public int quantity = 1;
    public int currencyItemID = 1;
  }
}