using System;
using System.Linq;
using Godot;
using Godot.Collections;

namespace Cirno.Scripts.Interactables;

public partial class Switch : Interactable
{
    [Export] public Node2D Target { get; set; }
    [Export] public Array<Node2D> Targets { get; private set; } = [];
    [Export] public ActivationType ActivationType { get; set; } = ActivationType.Toggle;
    
    [Signal]
    public delegate void OnActivatedEventHandler(ActivationType activationType);

    private AudioStreamPlayer2D _activationSound;

    private readonly string _activationSoundName = "ActivationSound";

    public override void _Ready()
    {
        _activationSound = GetNodeOrNull<AudioStreamPlayer2D>(_activationSoundName);
    }

    public override bool Activate(ActivationType activationType = ActivationType.Toggle)
    {
        ActivationType activationTypeToUse;
        if (activationType is ActivationType.Use)
        {
            activationTypeToUse = ActivationType;
        }
        else
        {
            activationTypeToUse = activationType;
        }
        
        if (!MeetsRequirements()) return false;
        _activationSound?.Play();
        
        EmitSignal(SignalName.OnActivated, (int)activationTypeToUse);
        
        // Compatibility for old single system
        bool success = ActivateTarget(Target, activationTypeToUse);

        return Targets.Aggregate(success, (current, target) => ActivateTarget(target, activationTypeToUse) | success);
    }

    private bool ActivateTarget(Node2D target, ActivationType activationType = ActivationType.Toggle)
    {
        if (target is not IActivable activable) return false;
        activable?.Activate(activationType);
        return true;
    }
}