### ----------------------------------------------------
### -- UpRooted
### -- Licenses: Artistic-2.0
### -- Authors: Paweł bbkr Pabian
### -- File: t/40-writer.rakutest
### ----------------------------------------------------
use lib 'lib';

use Test;

use UpRooted::Schema;
use UpRooted::Table;
use UpRooted::Column;
use UpRooted::Relation;
use UpRooted::Tree;
use UpRooted::Reader;
use UpRooted::Writer;

plan 10;

my @written;
class UpRooted::Writer::Dummy does UpRooted::Writer {

    method !write-start ( $tree, %conditions ) {
        
        @written.push: $tree;
        @written.push: %conditions;
    }
    
    method !write-table ( $table ) {
        
        @written.push: $table;
    }

    method !write-row ( @row ) {
        
        @written.push: @row;
    }
    
    method !write-flush ( ) {
        
        @written.push: 'flush';
    }
    
    method !write-end (  ) {
        
        @written.push: 'end';
    }
}

class UpRooted::Reader::Dummy does UpRooted::Reader {

    method !read-path ( $path, %conditions ) {
        
        given $path.leaf-table.name {
            when 't1' {
                take [ 1, 1 ]
            }
            when 't2' {
                take [ 1, 2 ];
                take [ 1, 3 ];
            }
        
        }
    }
}

my $schema = UpRooted::Schema.new( name => 's1' );
UpRooted::Table.new( :$schema, name => 't1' );
UpRooted::Table.new( :$schema, name => 't2' );
UpRooted::Column.new( table => $schema.table( 't1' ), name => 'c1', :!is-nullable );
UpRooted::Column.new( table => $schema.table( 't1' ), name => 'c2', :!is-nullable );
UpRooted::Column.new( table => $schema.table( 't2' ), name => 'c3', :!is-nullable );
UpRooted::Column.new( table => $schema.table( 't2' ), name => 'c4', :!is-nullable );
UpRooted::Relation.new(
    parent-columns => $schema.table( 't1' ).columns( 'c1' ),
    child-columns => $schema.table( 't2' ).columns( 'c3' ),
    name => 'r1'
);
my $tree = UpRooted::Tree.new( root-table => $schema.table( 't1' ) );
my $reader = UpRooted::Reader::Dummy.new( :$tree );
my $writer = UpRooted::Writer::Dummy.new;

$writer.write( $reader, c1 => 1 );

isa-ok @written.shift, UpRooted::Tree, 'UpRooted::Tree passed to write start';
is-deeply @written.shift, { 'c1' => 1 }, 'UpRooted::Conditions passed to write start';
is @written.shift, $schema.table( 't1' ), 'UpRooted::Root table passed to write table';
is-deeply @written.shift, [ 1, 1 ], 'UpRooted::Row from root UpRooted::Table passed to write row';
is @written.shift, 'flush', 'Flush called after last row of root UpRooted::Table';
is @written.shift, $schema.table( 't2' ), 'Leaf UpRooted::Table passed to write table';
is-deeply @written.shift, [ 1, 2 ], 'Row from leaf UpRooted::Table passed to write row';
is-deeply @written.shift, [ 1, 3 ], 'Row from leaf UpRooted::Table passed to write row';
is @written.shift, 'flush', 'Flush called after last row of leaf UpRooted::Table';
is @written.shift, 'end', 'Write end';


