
using Godot;
using System.Collections.Generic;

namespace Rokojori
{  
  [Tool][GlobalClass]
  public partial class LoadScene : SequenceAction
  {
    [Export]
    public string scenePath;

    [Export]
    public Node target;

    [Export]
    public Action onLoaded;

    bool _loading = false;
    int _id = -1;
    List<int> _cached = new List<int>();

    protected override void _OnTrigger()
    {
      if ( _loading )
      {
        _cached.Add( DispatchStart() );
        return;
      }

      _loading = true;
      _id = DispatchStart();
      var errorCode = ResourceLoader.LoadThreadedRequest( scenePath );

      if ( Error.Ok != errorCode )
      {
        _cached.Add( _id );
        _id = -1;
        _loading = false;
      }
    }

    public override void _Process ( double delta )
    {
      if ( ! _loading )
      { 
        return;
      }

      var status = ResourceLoader.LoadThreadedGetStatus( scenePath );

      if ( ResourceLoader.ThreadLoadStatus.Loaded != status )
      { 
        return;
      }

      _loading = false;
      
      var packedScene = (PackedScene) ResourceLoader.LoadThreadedGet( scenePath );
      var node = packedScene.Instantiate();
      target.AddChild( node );      
      Action.Trigger( onLoaded );
      DispatchEnd( _id );
      _id = -1;
    
      _cached.ForEach(
        ( c )=>
        {
          target.AddChild( packedScene.Instantiate() );      
          Action.Trigger( onLoaded );
          DispatchEnd( c );
        }
      );

      _cached.Clear(); 

    
    }
  }
}