#!/usr/bin/env perl
package Data::Resolver::Alternatives;
use v5.24;
use warnings;

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

extends 'Data::Resolver::Base';

has alternatives => (is => 'ro', required => 1);

sub _uniq_map ($self, $cb) {
   my %seen;
   grep { !$seen{$_}++ } map { $cb->($_) } $self->alternatives->@*;
}

sub _first ($self, $test) {
   $test->($_) && return $_ for $self->alternatives->@*;
   return;
}

sub get_asset ($self, $key) {
   my $provider = $self->_first(sub { $_[0]->has_asset($key) })
     or $self->not_found($key);
   return $provider->get_asset($key);
}

sub get_sub_resolver ($self, $key) {
   my $pr = $self->_first(sub { $_[0]->has_sub_resolver($key) })
     or $self->not_found($key);
   return $pr->get_sub_resolver($key);
}

sub has_asset ($self, $key) {
   !!($self->_first(sub { $_[0]->has_asset($key) }));
}

sub has_sub_resolver ($self, $key) {
   !!($self->_first(sub { $_[0]->has_sub_resolver($key) }));
}

sub list_asset_keys ($self) {
   $self->_uniq_map(sub ($resolver) { $resolver->list_asset_keys });
}

sub list_sub_resolver_keys ($self) {
   $self->_uniq_map(sub ($resolver) { $resolver->list_sub_resolver_keys });
}

1;
