#!/usr/bin/perl

use strict;
use CGI;
use JSON;

use Opals::Context;
use Opals::Constant;

use SIP::Map;
use SIP::Template;
use SIP::Session;
use SIP::Utility;

my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;

# $cgi->param('aaa') returns an array of aaa
my $input = $cgi->Vars();

#my $op = $input->{'op'};
my $util = SIP::Utility->new();

my $template = SIP::Template->new(filename => 'check_out.tmpl',);

my ($ok, $renewal_ok, $desensitize) = ('false', 'false', 'false');
my $due_date;
my $currency_type = substr($util->getPreference($dbh, 'currency'), 0, 3);

my $transaction_datetime = $util->now();
my @dt = split(/ /, $transaction_datetime);
my $transaction_date =~ $dt[0];

my $barcode = $input->{'item_identifier'};

my $session = SIP::Session->new(
  dbh               => $dbh,
  session_id        => $input->{'session_id'},
  patron_identifier => $input->{'patron_identifier'},
  item_identifier   => $barcode
);
$session->validate(
  patron_identifier => 1,
  account_expiry    => 1,
  item_identifier   => 1
);

my $screen_message = $session->get('screen_message');
my $user           = $session->get('user');
my $record         = $session->get('record');

if ($session->isValid()) {
  my @val;

  # cancel previous failed checkin
  if ($input->{'cancel'} eq 'Y') {
    @val = ($user->{'uid'}, $barcode);
    my $loan = $dbh->selectrow_hashref(<<_SQL_, undef, @val);
select  *
from    opl_loan
where   uid = ?
     && barcode = ?
order by idloan desc
limit 1 offset 0
_SQL_

    if ($loan->{'dateReturn'}) {
      @val = ($loan->{'idloan'});
      $dbh->do(<<_SQL_, undef, @val);
update  opl_loan
set     dateReturn = null
where   idloan = ?
_SQL_
    }
  }
  else {
    # loan: excluded params: duedate, command, loanType.
    my $loan = $util->post(
      url   => "http://$ENV{'HTTP_HOST'}/bin/ajax/circ/loan",
      param => [
        sip_sid      => $input->{'session_id'},
        uid          => $user->getUID(),
        barcode      => $barcode,
        itemCategory => 'Library'
      ]
    );

    if ($loan->is_success) {
      my $c = $loan->content;
      $c =~ s/\\'/'/g;
      my $r = decode_json $c;
      if ($r->{'loan'}->{'lid'} > 0) {
        $ok = 'true';
        $desensitize = 'true';
        $due_date = $r->{'loan'}->{'dateDue'};
      }
      else {
        # renewal
        my $renewal = $util->post(
          url   => "http://$ENV{'HTTP_HOST'}/bin/ajax/circ/renew",
          param => [
            sip_sid      => $input->{'session_id'},
            uid          => $user->getUID(),
            bcList       => $barcode,
            itemCategory => 'Library'
          ]
        );

        if ($renewal->is_success) {
          $c = $renewal->content;
          $c =~ s/\\'/'/g;
          $r = decode_json $c;
          my $rsc = $r->{'renewal'}->[0]->{'renewalStatusCode'};
          $rsc =~ s/renewalStatusCode_//;
          if ($rsc eq '01') {
            $ok = 'true';
            $desensitize = 'true';
            $due_date = $r->{'renewal'}->[0]->{'dateDue'};

            $renewal_ok = 'true';
          }
          else {
            $screen_message = SIP::Map::RENEWAL_STATUS_CODE->{$rsc}.'.';
          }
        }
        else {
          #extra error msg
          $screen_message = 'Error: '.$renewal->status_line.'.';
        }
      }
    }
    else {
      #extra error msg
      $screen_message = 'Error: '.$loan->status_line.'.';
    }
  }

  if ($ok eq 'false') {
    $screen_message .= ' Please see library staff for assistance.';
  }
}

# Tue, Jun 11, 2013 @ 10:49:57 EDT
# Test SIP2 extension media type
#$record->{'type'}='ebook';

my $response = {
  debug             => $session->get('debug'),
  ok                => $ok,
  renewal_ok        => $renewal_ok,
  magnetic_media    => SIP::Map::MAP->{ $record->{'type'} }->{'magnetic_media'},
  desensitize       => $desensitize,
  transaction_date  => $util->format_datetime($transaction_datetime, 'SIP'),
  institution_id    => $input->{'institution_id'},
  patron_identifier => $input->{'patron_identifier'},
  item_identifier   => $barcode,
  title_identifier  => $record->{'title'},
  currency_type     => $currency_type,
  due_date          => $util->format_datetime($due_date, 'SIP'),
  security_inhibit =>
    SIP::Map::MAP->{ $record->{'type'} }->{'security_inhibit'},
  media_type     => SIP::Map::MAP->{ $record->{'type'} }->{'media_type'},
  screen_message => $screen_message,
};

$template->param($response);

$template->write(cgi => $cgi);

################################################################################

sub _screen_message {
}
