#!/usr/bin/perl -w

use strict;
use Test::More no_plan => 1;
use Test::Exception;

use Parse::Reversable;

my $pr = Parse::Reversable->new( '/foo${FOO:\d+}/bar${BAR:\d+}' );

ok( defined $pr, 'defined $pr' );

my $vars;

$vars = $pr->parse( "/foo12/bar150" );
is_deeply( $vars, { FOO => 12, BAR => 150 }, 'parsed correct keys' );

$vars = $pr->parse( "/fooLETTER/bar150" );
is( $vars, undef, 'subpattern fail produces undef' );

$vars = $pr->parse( "/other" );
is( $vars, undef, 'literal mismatch produces undef' );

$vars = $pr->parse( " some substring /foo8/bar19 with extra junk " );
is( $vars, undef, 'correct keys with junk' );

my $str;

$str = $pr->build( { FOO => '85', BAR => '15' } );
is( $str, "/foo85/bar15", 'rebuilt string' );

$str = $pr->build( { FOO => 'one', BAR => 'two' } );
is( $str, "/fooone/bartwo", 'rebuilt string with mismatch patterns' );

# Allow trailing text

$pr = Parse::Reversable->new( 'nm${NAME:\w+}', allow_trail => 1 );

ok( defined $pr, 'defined $pr with trail' );

$vars = $pr->parse( "nmMyName" );
is_deeply( $vars, { NAME => 'MyName', _trail => '' }, 'parsed with empty trail' );

$vars = $pr->parse( "nmMyName with values" );
is_deeply( $vars, { NAME => 'MyName', _trail => ' with values' }, 'parsed with trail' );

dies_ok( sub { Parse::Reversable->new( '${NUM:\d+} + ${NUM:\d+}' ) },
         'Duplicate variable name fails' );
