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

public class UIInventorySlot : MonoBehaviour
{
	public TMPro.TextMeshProUGUI uiLabel, uiCount;
	public float spinSpeed = 100.0f;

	RectTransform rt;
	GameObject icon;
	Button button;

	public Item item { get; private set; }
	public int count { get; private set; }

	void Start()
    {
		rt = GetComponent<RectTransform>();
		button = GetComponent<Button>();
		if (uiLabel)
			uiLabel.text = "";
		if (uiCount)
			uiCount.text = "";
	}

	public void SelectItem() {
		if (item && isSlotSelectable)
			UIWrangler.selectedItem = item;
	}

	void SetLayerRecursively(GameObject obj, int newLayer) {
		obj.layer = newLayer;
		foreach (Transform child in obj.transform)
			SetLayerRecursively(child.gameObject, newLayer);
	}

	public bool isSlotSelectable {
		get {
			if (!button)
				return false;

			// Lock out non-disguises when we're disguised.
			bool wearingDisguise = UIWrangler.selectedItem && UIWrangler.selectedItem.GetComponent<Disguise>();
			if (wearingDisguise) {
				if (item) {
					bool isDisguise = item.GetComponent<Disguise>();
					return isDisguise;
				}
				return false;
			}

			return true;
		}
	}

	public void Set(Item _item, int _count) {
		if (icon) {
			GameObject.Destroy(icon);
			icon = null;
		}

		if (uiLabel)
			uiLabel.text = "";
		if (uiCount)
			uiCount.text = "";

		item = _item;
		count = _count;

		if (button)
			button.interactable = isSlotSelectable;

		if (item == null)
			return;

		if (uiLabel)
			uiLabel.text = item.label;
		if (uiCount && count != 1)
			uiCount.text = count.ToString();

		if (item) {
			icon = GameObject.Instantiate(item.gameObject);
			SetLayerRecursively(icon, LayerMask.NameToLayer("UI"));
			Transform tf = icon.transform;
			tf.SetParent(transform, true);

			// Compute local-space bounds.
			MeshFilter mf = icon.GetComponentInChildren<MeshFilter>();
			Vector3 localSize = mf.sharedMesh.bounds.size;

			Vector3 dir = (-Vector3.forward - Vector3.right*0.5f).normalized;

			// Re-scale it to fit.
			float sxz = rt.rect.width / Mathf.Max(localSize.x, localSize.z);
			float sy = rt.rect.height / localSize.y;
			float scale = Mathf.Min(sxz, sy);
			scale *= 0.6f; // add margin
			float objHeight = localSize.y*scale;
			tf.localRotation = Quaternion.LookRotation(dir);
			tf.localScale = new Vector3(scale, scale, scale);
			tf.localPosition = new Vector3(
				rt.rect.width*0.5f,
				(rt.rect.height - objHeight)*0.5f,
				-rt.rect.width);
		}
	}

    void Update()
    {
		if (icon && UIWrangler.ui.eventSystem.currentSelectedGameObject == gameObject)
			icon.transform.Rotate(0, UIWrangler.deltaTime*spinSpeed, 0);
	}
}
