
using Godot;


namespace Rokojori
{  
  [Tool]
  [GlobalClass, Icon("res://addons/rokojori_action_library/Icons/OnEvent.svg") ]
  public partial class OnTick : Node
  {
    
    [Export]
    public Action action;

    bool _active = false;

    [Export]
    public bool active
    {
      get => _active;
      set 
      {
        SetActive( value );
      } 
    } 

    [Export]
    public Duration tickDuration;
    
    [Export]
    public Duration offsetDuration;

    int _eventID = -1;

    [Export]
    public bool activateOnReady = false;

    public override void _Ready()
    {
      if ( ! Engine.IsEditorHint() && activateOnReady )
      {
        SetActive( true );

        this.LogInfo( "On Tick Started" );
      }
    }


    void SetActive( bool active )
    {
      if ( active == _active || Engine.IsEditorHint() )
      {
        return;
      }

      _active = active;

      var timeLine =  tickDuration.timeLine;

      if ( _active )
      { 
        var duration = tickDuration.GetDurationInSeconds();
        var offset   = offsetDuration == null ? 0 : offsetDuration.GetDurationInSeconds();

        // this.LogInfo( "duration", duration, "offset", offset );

        if ( _eventID != -1 )
        {
          TimeLineManager.RemoveEvent( timeLine, _eventID );
        }

        var tle = TimeLineManager.ScheduleLoopEvent( timeLine, duration, offset, tle => Action.Trigger( action ) ); 

        _eventID = tle.id;
      }
      else
      {
        this.LogInfo( "Removing tick:", _eventID );
        
        if ( _eventID == -1 )
        {
          return;
        }


        TimeLineManager.RemoveEvent( timeLine, _eventID );
        _eventID = -1;

       
      }

       

    }
  }
}