#!/usr/bin/perl

# Copyright 2016 Catalyst IT
# This file is part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Koha is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Koha; if not, see <http://www.gnu.org/licenses>.

use Modern::Perl;
use CGI qw ( -utf8 );
use JSON qw(encode_json);
use C4::Auth qw(checkauth);
use C4::Output qw( output_with_http_headers );
use Koha::Logger;
use Koha::ExternalContent::RecordedBooks;

our $cgi = CGI->new;
my $logger = Koha::Logger->get({ interface => 'opac' });
my $page_url = $cgi->referer();

my ( $user, $cookie, $sessionID, $flags ) = checkauth( $cgi, 1, {}, 'opac' );

my $action = $cgi->param('action') or response_bad_request("No 'action' specified");

($user && $sessionID) || $action eq 'search' or response_bad_request("User not logged in");

local $@;
my $rb = eval { Koha::ExternalContent::RecordedBooks->new({ koha_session_id => $sessionID }) };
unless ($rb) {
    $logger->error($@) if $@;
    response({
        error => $@,
        is_identified => JSON::false,
    });
}

my $is_identified = $rb->is_identified;
my %data = (
    is_identified => $is_identified ? JSON::true : JSON::false,
);
response(\%data) unless $is_identified || $action eq 'search';

eval {
    {
        $action eq 'search' && do {
            my $query = $cgi->param('q');
            my $page  = $cgi->param('page');
            my $page_size = $cgi->param('page_size');
            my $sort = $cgi->param('sort');
            my $res = $rb->search({
                query => $query,
                page  => $page,
                page_size => $page_size,
                sort => $sort,
            });
            $data{results} = $res;
            last;
        };

        $action eq 'account' && do {
            eval {
                $data{account} = $rb->patron;
                $data{checkouts} = $rb->checkouts;
                $data{holds} = $rb->holds;
            };
            response_bad_request($rb->error_message($@)) if $@;
            last;
        };

        $action eq 'checkout' && do {
            my $isbn = $cgi->param('isbn')
              or response_bad_request("No 'isbn' specified");
            my $format = $cgi->param('format');
            $data{action} = eval {  $rb->checkout($isbn, $format) };
            response_bad_request($rb->error_message($@)) if $@;

            eval {
                $data{checkouts} = $rb->checkouts;
                $data{holds} = $rb->holds;
            };
            $data{error} = $rb->error_message($@) if $@;
            last;
        };

        $action eq 'return' && do {
            my $isbn = $cgi->param('isbn')
              or response_bad_request("No 'isbn' specified");
            $data{action} = eval { $rb->return($isbn) };
            response_bad_request($rb->error_message($@)) if $@;

            $data{checkouts} = eval { $rb->checkouts };
            $data{error} = $rb->error_message($@) if $@;
            last;
        };

        $action eq 'place_hold' && do {
            my $isbn = $cgi->param('isbn')
              or response_bad_request("No 'isbn' specified");
            $data{action} = eval { $rb->place_hold($isbn) };
            response_bad_request($rb->error_message($@)) if $@;

            $data{holds} = eval { $rb->holds };
            $data{error} = $rb->error_message($@) if $@;
            last;
        };

        $action eq 'remove_hold' && do {
            my $isbn = $cgi->param('isbn')
              or response_bad_request("No 'isbn' specified");
            $data{action} = eval { $rb->remove_hold($isbn) };
            response_bad_request($rb->error_message($@)) if $@;

            $data{holds} = eval { $rb->holds };
            $data{error} = $rb->error_message($@) if $@;
            last;
        };

        response_bad_request("Invalid 'action': $action");
    }
};
if ($@) {
    $logger->error($@);
    $data{error} = $rb->error_message("$@");
}

response(\%data);


sub response_bad_request {
    my ($error) = @_;
    response({error => $error}, "400 $error");
}
sub response {
    my ($data, $status_line) = @_;
    $status_line ||= "200 OK";
    output_with_http_headers $cgi, undef, encode_json($data), 'json', $status_line;
    exit;
}
