package Catmandu::Fix::viaf_search;

use strict;
use warnings;

use Catmandu::Sane;
use Moo;
use Catmandu::Fix::Has;

use Catmandu::Util qw(:is);
use Catmandu::Fix::Datahub::Util qw(declare_source);

has path          => (fix_arg => 1);
has lang          => (fix_opt => 1, default => sub {'nl-NL'});
has fallback_lang => (fix_opt => 1, default => sub {'en-US'});

sub emit {
    my ($self, $fixer) = @_;
    my $perl = '';

    $perl .= 'use Catmandu::VIAF::API;';

    my $name = $fixer->generate_var();
    my $viaf = $fixer->generate_var();

    $perl .= "my ${name};";
    $perl .= declare_source($fixer, $self->path, $name);

    $perl .= "my ${viaf} = Catmandu::VIAF::API->new(term => ${name}, lang => '".$self->lang."');";

    $perl .= $fixer->emit_create_path(
        sub {
            my $root = shift;
            my $code = '';

            $code .= "${root} = ${viaf}->search();";

            return $code;

    return $perl;


=encoding utf-8

=head1 NAME

=for html <a href=""><img src=""></a>

Catmandu::Fix::viaf_match - Perform a search for a name in VIAF


  viaf_search(authorName, -lang:'nl-NL', -fallback_lang:'en-US')


Perform a search for a name. Both I<mainHeadingEl> and the
I<local.personalNames> are queried. The fix will return
the I<prefLabel> in the provided C<lang>, or C<fallback_lang> if one
in C<lang> does not exist. If C<fallback_lang> also doesn't exist, the
I<prefLabel> will be empty.

The fix returns a list, with elements in the following form:

    'dcterms:identifier' => 'The identifier',
    'guid'               => 'The VIAF URL',
    'schema:birthDate'   => 'Birth date, if provided',
    'schema:deathDate'   => 'Death date, if provided',
    'schema:description' => 'Description, if provided',
    'skos:prefLabel'     => 'prefLabel, in lang or fallback_lang'


=head3 Required parameters


=item C<path>

Path to the name.


=head3 Optional parameters


=item C<lang>

Language of the returned C<skos:prefLabel>. Falls back to
C<fallback_lang> if none was found. Use L<IETF language tags|>.

=item C<fallback_lang>

Fallback language.


=head1 AUTHOR

Pieter De Praetere E<lt>pieter at E<gt>


Copyright 2017- PACKED vzw

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=head1 SEE ALSO