#!perl

use Test::More;
use Test::Exception;
use autodie;

use Pg::Explain;

my $plan_source = q{Nested Loop Left Join  (cost=11.95..28.52 rows=5 width=157) (actual time=0.010..0.010 rows=0 loops=1)
  Output: rel_users_exams.user_username, rel_users_exams.exam_id, rel_users_exams.started_at, rel_users_exams.finished_at, exam_1.id, exam_1.title, exam_1.date_from, exam_1.date_to, exam_1.created, exam_1.created_by_, exam_1.duration, exam_1.success_threshold, exam_1.published
  Inner Unique: true
  Join Filter: (exam_1.id = rel_users_exams.exam_id)
  Buffers: shared hit=1
  ->  Bitmap Heap Scan on public.rel_users_exams  (cost=11.80..20.27 rows=5 width=52) (actual time=0.009..0.009 rows=0 loops=1)
        Output: rel_users_exams.user_username, rel_users_exams.exam_id, rel_users_exams.started_at, rel_users_exams.finished_at
        Recheck Cond: (1 = rel_users_exams.exam_id)
        Buffers: shared hit=1
        ->  Bitmap Index Scan on rel_users_exams_pkey  (cost=0.00..11.80 rows=5 width=0) (actual time=0.005..0.005 rows=0 loops=1)
              Index Cond: (1 = rel_users_exams.exam_id)
              Buffers: shared hit=1
  ->  Materialize  (cost=0.15..8.17 rows=1 width=105) (never executed)
        Output: exam_1.id, exam_1.title, exam_1.date_from, exam_1.date_to, exam_1.created, exam_1.created_by_, exam_1.duration, exam_1.success_threshold, exam_1.published
        ->  Index Scan using exam_pkey on public.exam exam_1  (cost=0.15..8.17 rows=1 width=105) (never executed)
              Output: exam_1.id, exam_1.title, exam_1.date_from, exam_1.date_to, exam_1.created, exam_1.created_by_, exam_1.duration, exam_1.success_threshold, exam_1.published
              Index Cond: (exam_1.id = 1)
Planning Time: 1.110 ms
Execution Time: 0.170 ms
};
my @source_lines = split( /\r?\n/, $plan_source );

plan 'tests' => 4 + scalar @source_lines;
my $explain = Pg::Explain->new( 'source' => $plan_source );
isa_ok( $explain,           'Pg::Explain' );
isa_ok( $explain->top_node, 'Pg::Explain::Node' );

lives_ok(
    sub {
        $explain->anonymize();
    },
    'Anonymization works',
);

my $textual = $explain->as_text();

my @anon_lines = split( /\r?\n/, $textual );

is( scalar @anon_lines, scalar @source_lines, "Anonymized output has the same number of lines" );
for my $i ( 0 .. $#{source_lines} ) {
    my $s_line = $source_lines[$i];
    my $a_line = $anon_lines[$i];
    my $s_indent = $s_line;
    my $a_indent = $a_line;
    $s_indent =~ s/\S.*//;
    $a_indent =~ s/\S.*//;
    is( $a_indent, $s_indent, "Indentation in line " . ( $i + 1 ) . " matches" )
}

exit;
