#!/usr/bin/env perl
package Data::Resolver::FromDir;
use v5.24;
use warnings;
use experimental 'signatures';
use English '-no_match_vars';

use File::Spec::Functions qw< catpath splitpath >;

use Moo;
no warnings 'experimental::signatures';
use namespace::clean;

extends 'Data::Resolver::Base';

has root   => (is => 'ro', required => 1);
has _split => (is => 'lazy');

sub _build__split ($self) { [(splitpath($self->root, 'no-file'))[0,1]] }

sub _child ($self, $key) { return catpath($self->_split->@*, $key) }

sub _children ($self, $test) {
   my $root = $self->root;
   opendir my $dh, $root
     or $self->complain(400, "opendir('$root'): $OS_ERROR");
   my @rv = readdir($dh)
     or $self->complain(400, "readdir('$root'): $OS_ERROR");
   closedir $dh
     or $self->complain(400, "closedir('$root'): $OS_ERROR");
   return grep { $test->($_) } @rv;
} ## end sub _children

sub get_asset ($self, $key) {
   my $child = $self->_child($key);
   $self->not_found($key) unless -f $child;
   return $self->asset($key => file => $child);
}

sub get_sub_resolver ($self, $key) {
   my $child = $self->_child($key);
   $self->not_found($key) unless -d $child;
   return $self->new(root => $child);
}

sub has_asset ($self, $key)        { -f ($self->_child($key) // '') }

sub has_sub_resolver ($self, $key) { -d ($self->_child($key) // '') }

sub list_asset_keys ($self) {
   my @sr = $self->_split->@*;
   $self->_children(sub ($item) { -f catpath(@sr, $item) });
}

sub list_sub_resolver_keys ($self) {
   my @sr = $self->_split->@*;
   $self->_children(sub ($item) { -d catpath(@sr, $item) });
}

1;
