package SLUB::LZA::Rosetta::TA::SRU;
use strict;
use warnings;
use feature qw(say);
use LWP::Authen::Basic;
use LWP::UserAgent;
use LWP::ConsoleLogger::Easy qw( debug_ua );
use Carp;
use namespace::autoclean;

# VERSION

# ABSTRACT: module to handle SRU requests for ta-tool

sub url_encode_simple {
    my $string = shift;
    $string =~ s/ /%20/g;
    $string =~ s/"/%22/g;
    $string =~ s/'/%27/g;
    $string =~ s/:/%3a/g;
    return $string;
}

sub sru_search {
    my $searchtype = shift;
    my $unencoded_query = shift;
    my $query = url_encode_simple($unencoded_query);
    my $startrecord = shift;
    my $maxrecords = shift;
    my $is_verbose = shift;
    my $is_debug = shift;
    my %searchpaths = (
        ie   => 'permanent/ie',
        file => 'permanent/file',
        sip  => 'operational'
    );

    if (!exists $searchpaths{$searchtype}){
        croak ("Code error, wrong searchtype ($searchtype) used!");
    }
    my $host = $SLUB::LZA::Rosetta::TA::config{host};
    my $protocol = 'https';
    my $port = '8443';
    if (defined $SLUB::LZA::Rosetta::TA::Command::config{httponly}) {
        $protocol = 'http';
        $port = '1801';
    }
    my $searchpath = $searchpaths{$searchtype};
    my $srubase="${protocol}://${host}:${port}/search/${searchpath}/sru";
    my $sru = "${srubase}?version=1.2&operation=searchRetrieve&startRecord=$startrecord&maximumRecords=$maxrecords&recordSchema=dc&query=${query}";
    my $ua = LWP::UserAgent->new(keep_alive => 1);
    $ua->agent("MyApp/0.1 ");
    $ua->timeout(3600);#1h
    $ua->default_headers->push_header('Accept-Encoding' => 'br, lzma, bzip2, gzip, compressed, deflate');


    $ua->ssl_opts(
        verify_hostname=>1,
        # SSL_ca_path => '/etc/ssl/',
    );

    if ($is_verbose) {
        say "searchurl = $sru";
    }
    foreach my $retry (1 .. 2) {
        my $console_logger = debug_ua( $ua ) unless (! $is_debug);
        my $req = $ua->get($sru);
        if ($req->is_success) {
            my $xres = $req->decoded_content;
            return $xres;
        } else {
            if ($retry == 1 and defined $SLUB::LZA::Rosetta::TA::config{"decrypted_password"} ) {
                my $user = $SLUB::LZA::Rosetta::TA::config{"user"};
                my $inst = $SLUB::LZA::Rosetta::TA::config{"institution"};
                my $password = $SLUB::LZA::Rosetta::TA::config{"decrypted_password"};
                my $preauth = "$user-institutionCode-$inst:$password";
                my $auth = MIME::Base64::encode_base64($preauth , '');
                $ua->default_headers->push_header('Authorization' => $auth);
                warn "Retry using authentication";
            } else {
                croak("Error was: " . $req->status_line());
            }
        }
    }
}

1;
