using UnityEngine;
using System.Collections;

[CreateAssetMenu(fileName = "Item Action Plant Seed", menuName = "Items/Item Actions/Plant Seed")]
public class ItemAction_PlantSeed : ItemAction
{
    [SerializeField]
    private SaveablePrefab plantablePrefab;

    [SerializeField]
    private ScriptableReference gridManagerReference;

    [SerializeField]
    private string requiredGrid;

    private GridManager gridManager;

    private GridManager GetGridManager()
    {
        if (gridManager == null)
        {
            gridManager = gridManagerReference.Reference.GetComponent<GridManager>();
        }

        return gridManager;
    }

    public override IEnumerator ItemUseAction(Inventory userInventory, int itemIndex)
    {
        yield return null;

        InventoryItem getItem = userInventory.GetItem(itemIndex);

        if (PlantAction(userInventory))
        {
            getItem.Amount -= 1;

            if (getItem.Amount <= 0)
            {
                userInventory.RemoveItem(itemIndex);
            }
            else
            {
                userInventory.ReloadItem(itemIndex);
            }
        }
    }

    private bool PlantAction(Inventory userInventory)
    {
        GridSelector gridSelector = userInventory.GetComponent<GridSelector>();
        Vector3Int selectionLocation = gridSelector.GetGridSelectionPosition();

        Vector3 loc = gridSelector.GetGridWorldSelectionPosition();

        RaycastHit2D[] findObjects = Physics2D.BoxCastAll(loc, GetGridManager().Grid.cellSize * 0.5f, 0, Vector2.zero, 50);

        for (int i = 0; i < findObjects.Length; i++)
        {
            if (findObjects[i].transform.CompareTag("Crop"))
                return false;
        }

        if (GetGridManager().ContainsMapsAtLocation(new string[] { requiredGrid }, selectionLocation))
        {
            GameObject gameObject = plantablePrefab.Retrieve<GameObject>();
            gameObject.transform.position = GetGridManager().GetWorldLocation(selectionLocation);
            return true;
        }
        else
        {
            return false;
        }
    }

    public override bool ItemUseCondition(Inventory userInventory, int itemIndex)
    {
        bool hasEnoughItems = userInventory.GetItem(itemIndex)?.Amount <= 0;

        if (!hasEnoughItems)
        {
            userInventory.RemoveItem(itemIndex);
        }

        return hasEnoughItems;
    }
}
