{% set assign=true %}
{% set signal=true %}
{% set resolve=true %}

{% import "src/default/types/block.js.njk" as block with context %}

{% call block.header() %}
{% endcall %}

{% call block.definition() %}

  {% if context.next %}

    // NEXT : {{context.next.indexKey}}
    {% if context.next.definition.dynamic %}
      const { default: {{context.next.codeKey}} } = await import("./{{context.next.codeKey}}.js");
    {% endif %}

    let current=new {{context.next.codeKey}}({ parent:_this, engine, flow, caller:c , error });
    let currentArgs=args;

    do {

      {% if workflow.parent.context.atom.doc.features.print_runners %}
        console.log(new Date().toLocaleString(),' * ',_this.constructor.IndexKey,' -> ',current.constructor.IndexKey);
      {% endif %}

      const nextBlock= typeof currentArgs==='undefined'? await current.run()
        : Array.isArray(currentArgs)? await current.run.apply(current,currentArgs) : await current.run(currentArgs) ;

      if(nextBlock?.type==='return') return resolve(nextBlock);
      else if(nextBlock?.type!=='block') break;

      if(nextBlock.toType.ParentTypeId!==_this.constructor.TypeId)
        return resolve(nextBlock);

      current=new nextBlock.toType({ parent:_this, engine, flow, caller:c, error });
      currentArgs=nextBlock.input;

    } while(true);

  {% endif %}
  
{% endcall %}

{% call block.footer()%} 
{% endcall %}