use v6.d;
use Test;
use RakuDoc::Render;

plan 15;

my $ast;
my $rv;
my RakuDoc::Processor $rdp .= new( :test );

$ast = Q:to/QAST/.AST;
    =begin rakudoc
    =config head2 :!toc
    =head2 Third test text
    =end rakudoc
    QAST
$rv = $rdp.render( $ast, :pre-finalised );
is $rv.toc.elems, 0, 'No toc registered';
like $rv.body.Str, /'<head>' .+ 'level' .+ 2 .+ '</head>' /, 'But heads rendered at level 2';
$ast = Q:to/QAST/.AST;
    =head2 First header
    =begin section
    =head2 Second header without option
    =config head2 :!toc
    =head2 Third test text with option
    =end section
    =head2 Fourth without option
    QAST
$rv = $rdp.render( $ast, :pre-finalised );
my regex hd { '<head>' $<cont> = (.+?) '</head>' }
my $parse = $rv.body.Str ~~ / [<hd> .*? ]+ $/;
is $parse<hd>.elems, 4, 'got 4 heads';
is $rv.toc.elems, 3, 'Only three heads in toc';
like $parse<hd>[0]<cont>, / 'contents' .+ 'First header' /, 'Got first head';
like $parse<hd>[1]<cont>, /'contents' .+ 'Second header' /, 'got 2nd head';
like $parse<hd>[2]<cont>, /'contents' .+ 'Third test text' /, '3rd head is rendered';
like $parse<hd>[3]<cont>, / 'Fourth without option'  /, '4th head rendered';

$ast = Q:to/QAST/.AST;
    =begin rakudoc
    =head First header
    =head2 Second header
    =head2 Third test
    =for formula :toc<Forms> :caption<Eq One>
    E = mc²
    =for formula :caption<Not in TOC>
    E = mc²
    =end rakudoc
    QAST
$rv = $rdp.render( $ast, :pre-finalised );
is $rv.toc.elems, 4, 'toc structure has 4 elems';
is $rv.toc.grep({ .<toc-type> eq 'head' }).elems, 3, 'only three head elems';
is $rv.toc.grep({ .<toc-type> eq 'Forms' }).head.<caption>, 'Eq One', 'got the correct caption';
$ast = Q:to/QAST/.AST;
    =begin rakudoc
    =head First header
    =head2 Second header
    =head2 Third test
    =for formula :toc<Forms> :caption<Eq One>
    E = mc²
    =for table  :toc<Forms> :caption<Table in Form TOC>
    | one | two |
    =end rakudoc
    QAST
$rv = $rdp.render( $ast, :pre-finalised );
is $rv.toc.elems, 5, 'toc structure has 5 elems';
is $rv.toc.grep({ .<toc-type> eq 'Forms' }).elems, 2, 'Forms has 2 elems';
is $rv.toc.grep({ .<toc-type> eq 'Forms' }).tail.<caption>, 'Table in Form TOC', 'got the correct caption';

# test rakudoc toc autogen
$ast = q:to/QAST/.AST;
    =begin rakudoc
    =head This is a header

    content
    =end rakudoc
    QAST

$rv = $rdp.render( $ast, :pre-finalised );
like $rv.rendered-toc, / 'This is a header' /, 'ToC is rendered';

# test turn off render in ddd-document-directive.rakutest
done-testing;
