using System;
using Babushka.scripts.CSharp.Common.CharacterControls;
using Babushka.scripts.CSharp.Common.Inventory;
using Godot;
namespace Babushka.scripts.CSharp.Common.Farming;
[GlobalClass]
public partial class FieldBehaviour2D : Sprite2D
{
[Export] private Sprite2D _fieldSprite;
[Export] private Sprite2D _maskSprite;
[Export] private Texture2D[] _maskTexture;
[Export] private Texture2D Tilled;
[Export] private Texture2D Watered;
[Export] public FieldState FieldState = FieldState.Tilled;
[Export] public InteractionArea2D PlantingInteraction;
[Export] public Node2D PlantingPlaceholder;
[Export] public ItemRepository ItemRepository;
public Vector2 FieldPosition;
public override void _Ready()
{
UpdateFieldState(FieldState);
int randomIndex = new Random().Next(0, _maskTexture.Length);
_maskSprite.Texture = _maskTexture[randomIndex];
base._Ready();
}
public void UpdateFieldState(FieldState state)
{
switch (state)
{
case FieldState.Empty:
FieldState = FieldState.Empty;
PlantingInteraction.IsActive = false;
break;
case FieldState.Tilled:
FieldState = FieldState.Tilled;
_fieldSprite.Texture = Tilled;
PlantingInteraction.IsActive = true;
break;
case FieldState.Watered:
FieldState = FieldState.Watered;
_fieldSprite.Texture = Watered;
PlantingInteraction.IsActive = true;
break;
case FieldState.Planted:
FieldState = FieldState.Planted;
_fieldSprite.Texture = Tilled;
PlantingInteraction.IsActive = false;
break;
default:
FieldState = FieldState.NotFound;
break;
}
}
public void Water()
{
UpdateFieldState(FieldState.Watered);
}
///
/// Called when the player enters the field's interaction area and presses .
///
public void Farm()
{
if (TryPlant())
{
UpdateFieldState(FieldState.Planted);
}
}
private bool TryPlant()
{
bool success = false;
int currentSlotIndex = InventoryManager.Instance.CurrentSelectedSlotIndex;
ItemInstance? item = InventoryManager.Instance.playerInventory.Slots[currentSlotIndex].itemInstance;
if (item == null || PlantingPlaceholder.GetChildCount() > 0 || item.amount == 0)
return success;
string prefabPath = ItemRepository.TryGetPrefabPath(item.blueprint);
if (prefabPath != null)
{
PackedScene prefab = ResourceLoader.Load(prefabPath, nameof(PackedScene));
Node2D plant2d = prefab.Instantiate();
PlantingPlaceholder.AddChild(plant2d);
plant2d.GlobalPosition = PlantingPlaceholder.GlobalPosition;
PlantBehaviour2D? plantBehaviour = plant2d as PlantBehaviour2D;
if (plantBehaviour != null)
{
plantBehaviour.Field = this;
}
InventoryManager.Instance.playerInventory.RemoveItem(currentSlotIndex);
success = true;
}
return success;
}
}