using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System;
using Multiplayer;

public class Recipe : MonoBehaviour {

    Player localPlayer;
    int PlayerCount;
    public Vegetable[] Veggies;
    public Frame[] Frames;

    public int[] Qtys;
    public int[] heldQtys;

    public GameObject RecipeCanvas;

    public Image Inventory;

	// Use this for initialization
	void Start () {

        localPlayer = PlayersManager.Instance.LocalPlayer.Player;
        PlayerCount = PlayersManager.Instance.Players.Count;

        localPlayer.GetComponent<LocalPlayer>().recipe = this;
        for (int i = 0; i < PlayerCount; i++)
        {
            int rand = UnityEngine.Random.Range(0, Qtys.Length - 1);
            Qtys[rand] += 1;
        }
        for (int i = 0; i < 4; i++) //Set the recipe UI
        {
            Frames[i].VegetableSpot.sprite = Veggies[i].Image;
            Frames[i].Qty.text = Qtys[i] + "";
        }
    }

    private void OnEnable()
    {
        ClientManager.Instance.Client.RegisterHandler(PlayerMsgID.Vegetable, recieveVeg);
    }

    private void OnDisable()
    {
        ClientManager.Instance.Client.UnregisterHandler(PlayerMsgID.Vegetable);
    }

    //Button calls
    public void OpenRecipe()
    {
        RecipeCanvas.SetActive(true);
    }

    public void CloseRecipe()
    {
        RecipeCanvas.SetActive(false);
    }

    //Veggie interactions
    public void pickupItem(Vegetable newVeggie)
    {
        Inventory.gameObject.SetActive(true);
        Inventory.sprite = newVeggie.Image;
    }


    public void friendlyPickup(string VeggieName, int change)
    {
        StartCoroutine(ItemLookup(VeggieName, change));

        VegMsg msg = new VegMsg(ClientManager.Instance.ID, VeggieName, change);
        ClientManager.Instance.SendMessage(PlayerMsgID.Vegetable, msg);
    }

    public void recieveVeg(UnityEngine.Networking.NetworkMessage msg)
    {

        VegMsg vegMsg;
        if (!Utility.ReadMessage<VegMsg>(msg, out vegMsg))
            return;

        StartCoroutine(ItemLookup(vegMsg.String, vegMsg.Int));
    }

    IEnumerator ItemLookup(string VeggieName, int change)
    {
        for (int i = 0; i < Veggies.Length; i++)
        {
            if(Veggies[i].Name == VeggieName)
            {
                heldQtys[i] += change;
            }
        }
        yield return new WaitForEndOfFrame();
    }

    public bool CheckVictory()
    {
        bool winning = true;
        for (int i = 0; i < Veggies.Length; i++)
        {
            if (Qtys[i] != heldQtys[i])
            {
                winning = false;
            }
        }
        return winning;
    }
}



[Serializable]
public class Vegetable
{
    public string Name;
    public Sprite Image;
}

[Serializable]
public class Frame
{
    public Image VegetableSpot;
    public TextMeshProUGUI Qty;
}