using System.Linq;
using Cirno.Scripts.Interactables;
using Godot;

namespace Cirno.Scripts.Components.FSM.Player;

public partial class AutoPickupModule : PlayerArea2DModule
{
    private bool _enabled = false;

    public bool Enabled
    {
        get => _enabled;
        set
        {
            if (_enabled == value) return;
            _enabled = value;
            // if (_enabled)
            // {
            //     EmitSignal(SignalName.InteractionStarted);
            // }
        }
    }
    
    public override void Init(IStateMachine<PlayerState, CharacterBody2D> machine)
    {
        base.Init(machine);
    }

    public override void EnterState(PlayerState state)
    {
        Enabled = true;
        this.AreaEntered += _on_area_entered;
    }

    public override void ExitState(PlayerState state)
    {
        Enabled = false;
        this.AreaEntered -= _on_area_entered;
    }

    public override void Process(double delta)
    {

    }

    public override void PhysicsProcess(double delta)
    {

    }
    
    private void _on_area_entered(Area2D area)
    {
        if (!Enabled) return;
        if (area is ItemPickup { AutoPickup: true } itemPickup)
        {
            //Check if items are not maxed to avoid a looping autopickup situation
            var canAdd = itemPickup.LootTable.Aggregate(false, (current, item) => current || InventoryManager.Instance.CanAddItem(item.ItemKey));

            if (canAdd)
            {
                itemPickup.Collect();
            }
        }
    }
}