#!/usr/bin/env perl
use v5.24;
use warnings;
use experimental 'signatures';

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

use File::Basename 'dirname';
use lib dirname(__FILE__);    # basic functions

lives_ok {
   require Data::Resolver::FromDir;
   require Data::Resolver::FromTar;
   require Data::Resolver::Alternatives;
   1;
} ## end lives_ok
'requiring applicable modules' or BAIL_OUT 'cannot load base class';

use DRTestBasics 'sibling';

my $datafile = sibling(__FILE__, '40-resolver-fromtar-class.tar');
my $datadir  = sibling(__FILE__, '50-resolver-alternatives-class.d/');

ok -f $datafile, "data file for tests exists";
ok -d $datadir,  "data dir for tests exists";

my $resolver;
lives_ok {
   $resolver = Data::Resolver::Alternatives->new(
      alternatives => [
         Data::Resolver::FromTar->new(root => $datafile),
         Data::Resolver::FromDir->new(root => $datadir),
      ]
   );
} ## end lives_ok
'call to constructor lives';
isa_ok $resolver, 'Data::Resolver::Alternatives';

my @asset_keys;
lives_ok { @asset_keys = $resolver->list_asset_keys } 'list_asset_keys';
is scalar(@asset_keys), 2, 'no. of asset keys'
  or diag("asset_keys(@asset_keys)");

my ($first, $second) = sort { $a cmp $b } @asset_keys;
is $first, 'ciao.txt', 'first asset key';
ok $resolver->has_asset($first), 'has first asset';
like $resolver->get_asset($first)->raw_data, qr{(?mxs:\A ciao \s*\z)},
  'data from first asset (tar)';

is $second, 'onlydir.txt', 'second asset key';
ok $resolver->has_asset($second), 'has second asset';
like $resolver->get_asset($second)->raw_data, qr{(?mxs:\Athis.*only\s*\z)},
  'data from second asset (dir)';

my @subr_keys;
lives_ok { @subr_keys = $resolver->list_sub_resolver_keys }
'list sub-resolver keys';

# keep only "portable" stuff
@subr_keys = sort { $a cmp $b } grep { ! m{\W}mxs } @subr_keys;
is scalar(@subr_keys), 2, 'no. of sub-resolver keys'
   or diag("sub_resolver_keys(@subr_keys)");
is_deeply \@subr_keys, [qw< foo kitno >], 'sub-resolver keys';

my $subr1 = $resolver->get_sub_resolver('foo');
isa_ok $subr1, 'Data::Resolver::FromTar';

my $subr2 = $resolver->get_sub_resolver('kitno');
isa_ok $subr2, 'Data::Resolver::FromDir';

my $asset = $subr1->get_asset('bar.txt');
my $data = $asset->raw_data =~ s{\s+}{}rgmxs;
is $data, 'baz', 'contents of asset in tar sub-resolver';

$asset = $subr2->get_asset('also.txt');
$data = $asset->raw_data =~ s{\s+}{}rgmxs;
is $data, 'also', 'contents of asset in dir sub-resolver';

done_testing();
