#!perl

use strict;
use warnings;

use Test::More;
use Test::BDD::Cucumber::Parser;
use Test::Differences;

use Path::Class qw/file dir/;
use JSON::MaybeXS qw/decode_json/;

my $test_dir = dir('t/gherkin-acceptance-tests/good/');
my @test_names;
while ( my $file = $test_dir->next ) {
    push( @test_names, $1 ) if $file =~ m!/(\w+)\.feature$!;
}

for my $test_name (@test_names) {

    my $feature = Test::BDD::Cucumber::Parser->parse_file(
        $test_dir->file( $test_name . '.feature' ) );

    ok( $feature, "$test_name parses");

    next;

}

done_testing();

__DATA__

    my $ast = {
        type     => 'Feature',
        name     => $feature->name,
        tags     => [],
        location => convert_line( $feature->name_line ),
        keyword  => $feature->keyword,
        comments => [],
        language => $feature->language,
    };

    if ( $feature->background ) {
        $ast->{'background'}
            = convert_scenario( Background => $feature->background )
            if $feature->background;
    }

    $ast->{'scenarioDefinitions'}
        = [ map { convert_scenario( 'Scenario', $_ ) }
            @{ $feature->scenarios } ];

    my $expected
        = decode_json
        scalar $test_dir->file( $test_name . '.feature.ast.json' )->slurp;

    eq_or_diff( $ast, $expected, $test_name );

}

done_testing();

sub convert_scenario {
    my ( $type, $scenario ) = @_;
    my $return = {
        name     => $scenario->name,
        keyword  => $scenario->keyword,
        type     => $type,
        location => convert_line( $scenario->line ),
        steps    => convert_steps( $scenario->steps ),
        ( $type eq 'Background' ? () : ( tags => [] ) ),
    };

}

sub convert_steps {
    my ($steps) = @_;
    return [
        map {
            my $return = {   type     => 'Step',
                keyword  => $_->verb_original . ' ',
                location => convert_line( $_->line ),
                text     => $_->text,
            };
            if ( ref $_->data eq 'ARRAY' ) {
                use Data::Printer;
                die p $_->data_as_strings;
            }
        } @$steps
    ];
}

sub convert_line {
    my ($line) = @_;
    return {
        column => 1 + $line->indent,
        line   => $line->number,
    };
}
