using Godot;

namespace Cirno.Scripts.Misc;

public partial class DialogueAutoStarter : Node2D
{
    [Export] private StringName _trackName = "timeline";
    [Export] private StringName _finishedScenePath;

    [Export] public StringName PauseActionName { get; private set; } = "pause";
    
    private Node _dialogic;

    private bool _dialogueActive = false;
    
    public override void _Ready()
    {
        base._Ready();
        
        _dialogic = GetNode("/root/Dialogic");
        _dialogic.ProcessMode = ProcessModeEnum.Always;

        CallDeferred(MethodName.Activate);
    }

    public override void _Process(double delta)
    {
        if (!_dialogueActive) return;
        if (Input.IsActionJustPressed(PauseActionName))
        {
            _dialogic.Call("end_timeline");
        }
    }

    private void OnTimelineEnded()
    {
        if (_dialogic.IsConnected("timeline_ended", Callable.From(OnTimelineEnded)))
        {
            _dialogic.Disconnect("timeline_ended", Callable.From(OnTimelineEnded));
        }
        
        DialogueEndAction();
    }
    
    public bool Activate()
    {
        _dialogueActive = true;
        
        if (GlobalState.Instance.SessionSettings.SkipDialogues)
        {
            DialogueEndAction();
            return true;
        }
        _dialogic.Connect("timeline_ended", Callable.From(OnTimelineEnded));
        
        var dialogicNode = _dialogic.Call("start", _trackName.ToString());
        ((Node)dialogicNode).ProcessMode = ProcessModeEnum.Always;
        
        return true;
        
    }

    private void DialogueEndAction()
    {
        _dialogueActive = false;
        GlobalState.Instance.GotoScene(_finishedScenePath);
    }
}