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

public class Inventory : MonoBehaviour
{
    public List<SpaceObject> items;
    public Transform itemContainer;
    public InventorySlot selectedSlot;

    private void Awake()
    {
        
    }

    private void Start()
    {
        for (int i = 0; i < transform.childCount; i++)
        {
            Transform childTransform = transform.GetChild(i);
            SpaceObject spaceObject = childTransform.GetComponent<SpaceObject>();
            Debug.Log(spaceObject.name);
            AddToInventory(spaceObject);
        }

        StartCoroutine(Bodge2());
        
    }

    public bool IsItemInInventory(SpaceObject spaceObject)
    {
        return items.Contains(spaceObject);
    }

    public void AddToInventory(SpaceObject spaceObject)
    {
        StartCoroutine(Bodge(spaceObject));
    }

    private IEnumerator Bodge(SpaceObject spaceObject)
    {
        yield return new WaitForEndOfFrame();
        items.Add(spaceObject);
        spaceObject.gameObject.layer = LayerMask.NameToLayer("Inventory");
        if (spaceObject.icon != null)
            spaceObject.icon.HideIcon();
        GameManager.instance.engine.RefreshRepairButton();


    }

    private IEnumerator Bodge2()
    {
        yield return new WaitForEndOfFrame();
        yield return new WaitForEndOfFrame();
        for (int i = 0; i < items.Count; i++)
        {
            GameManager.instance.inventorySlots[i].SetItem(items[i]);
        }
    }

    public SpaceObject RemoveFromInventory(SpaceObject spaceObject)
    {
        if (items.Contains(spaceObject) == false) return null;
        items.Remove(spaceObject);
        spaceObject.gameObject.layer = LayerMask.NameToLayer("Environment");
        spaceObject.icon.ShowIcon();
        GameManager.instance.engine.RefreshRepairButton();
        return spaceObject;
    }

    public void SetSelectedInventorySlot(InventorySlot slot)
    {
        selectedSlot = slot;        
        RefreshEjectButtons();
    }

    private void RefreshEjectButtons()
    {
        if (selectedSlot == null)
        {
            GameManager.instance.ejectForwardButton.SetActive(false);
            GameManager.instance.ejectBackwardButton.SetActive(false);
        }
        else
        {
            GameManager.instance.ejectForwardButton.SetActive(true);
            GameManager.instance.ejectBackwardButton.SetActive(true);
        }
    }
}
