using Godot;
using Godot.Collections;

namespace Cirno.Scripts.Activables;

public partial class DialogueStarter : ChainActivable
{
    
    [Export] private string _trackName = "timeline";
    [Export] public StringName PauseActionName { get; private set; } = "pause";
    //[Export] private Array<Node2D> _dialogueEndActivationTargets;
    
    private Node _dialogic;
    
    private GameManager _gameManager;
    private bool _dialogueActive = false;
    
    public override void _Ready()
    {
        base._Ready();

        _gameManager = this.GetGameManager();
        
        _dialogic = GetNode("/root/Dialogic");
        _dialogic.ProcessMode = ProcessModeEnum.Always;
    }
    
    public override void _Process(double delta)
    {
        if (!_dialogueActive) return;
        if (Input.IsActionJustPressed(PauseActionName))
        {
            _dialogic.Call("end_timeline");
        }
    }

    private void OnTimelineEnded()
    {
        _gameManager.ChangeState(GameState.Playing);
       if (_dialogic.IsConnected("timeline_ended", Callable.From(OnTimelineEnded)))
        {
            _dialogic.Disconnect("timeline_ended", Callable.From(OnTimelineEnded));
        }
        
        DialogueEndAction();
    }
    
    public override bool Activate(ActivationType activationType = ActivationType.Toggle)
    {
        _dialogueActive = true;
        if (GlobalState.Instance.SessionSettings.SkipDialogues)
        {
            DialogueEndAction();
            return true;
        }
        
        Hud.Instance?.HideHud();
        
        _dialogic.Connect("timeline_ended", Callable.From(OnTimelineEnded));
        
        var dialogicNode = _dialogic.Call("start", _trackName);
        ((Node)dialogicNode).ProcessMode = ProcessModeEnum.Always;
        _gameManager.ChangeState(GameState.Dialogue);
        
        return true;
        // Script dialogic = ResourceLoader.Load("res://addons/dialogic/Other/DialogicClass.gd") as Script;
        // var dialog = (Node) dialogic.Call("start","timeline");	
        // AddChild(dialog);	
        //if (Dialogic)
    }

    private void DialogueEndAction()
    {
        _dialogueActive = false;
        Hud.Instance?.HideHud();
        _gameManager.ChangeState(GameState.Playing);
        ActivateTargets();
        // foreach (var activationTarget in _dialogueEndActivationTargets)
        // {
        //     ActivateTarget(activationTarget);
        // }
    }

    // private bool ActivateTarget(Node2D activationTarget)
    // {
    //     if (activationTarget is not IActivable target)
    //     {
    //         GD.PrintErr($"Target {activationTarget.Name} is not activable");
    //         return false;
    //     }
    //     
    //     target?.Activate();
    //     
    //     GD.Print($"{activationTarget.Name} activated");
    //
    //     return true;
    // }
}