#!/usr/bin/perl
#
# TODO: Add/delete function has been removed. Script and template need cleanup.
#
#use utf8;
use strict;
use CGI;

use Opals::Context;
use Opals::Template qw(
  tmpl_searchFieldOrder
  tmpl_read
  tmpl_write
);

#    $searchField
#    $sfIndex

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

my $cgi   = CGI->new;
my $input = $cgi->Vars();

my ($permission, $cookie, $template) = tmpl_read(
  {
    dbh           => $dbh,
    cgi           => $cgi,
    tmplFile      => 'util/syspref.tmpl',
    reqPermission => 'pref_edit',
  }
);

if ($input->{'act'} && $input->{'act'} eq 'edit') {
  my $KeyVal = $input->{'keyval'};
  my $dataRow = LoadItem($dbh, $KeyVal);

  $template->param(ebookSetUp => 1) if ($KeyVal eq "ebookModule");
  if ($KeyVal eq "ebookModule") {
    my $ebs_host_params    = LoadItem($dbh, "ebs_host");
    my $ebs_libCode_params = LoadItem($dbh, "ebs_libCode");
    $template->param(ebookSetUp_empty => 1)
      if ($ebs_host_params->{'val'} eq ""
      || $ebs_libCode_params->{'val'} eq "");

  }
  $template->param(EditItem => 1);
  $dataRow->{'varType'} = 'text'
    if (!defined $dataRow->{'varType'} || $dataRow->{'varType'} eq '');
  if ($dataRow->{'varType'} eq 'timeLength') {
    if ($dataRow->{'val'} =~ m/(\d+)([\w])/g) {
      $template->param(timeLength => $1);
    }
  }
  my $varInpuType = "varType_" . $dataRow->{'varType'};
  $template->param($varInpuType => 1);

  while (my ($key, $value) = each(%$dataRow)) {
    $template->param($key => $value);
  }
  my $valParamList = getValParamList($dbh, $KeyVal);
  $template->param(valParamList => $valParamList);
  tmpl_write($dbh, $cgi, $cookie, $template);
  goto __END_OF_FILE;
}

if ($input->{'act'} && $input->{'act'} eq 'update') {

  update_var($dbh);
  if ($input->{'var'} ne 'useAttOrder') {
    $template->param($input->{'var'} => $input->{'val'});
  }
  else {
    my ($searchField, $sfIndex) = tmpl_searchFieldOrder($input->{'val'});
    my $sf0;
    ($sf0 = $cgi->cookie('sf0')) || ($sf0 = 1016);
    $template->param(
      sf  => $searchField,
      sfi => $sfIndex->{$sf0},
    );
  }
}

# Ha: Fri, Oct 09, 2009 @ 14:35:22 EDT
# Get new preference by group
getPrefListGroup();
$template->param(hlpUrl => Opals::Constant->getHlpUrl('syspref'));

$template->param(scriptname => 'syspref');
tmpl_write($dbh, $cgi, $cookie, $template);

#-------------------------------------------------------------

sub LoadItem {
  my ($dbh, $var) = @_;

  # Create SQL command
  my $sth = $dbh->prepare("select * from opl_preference where var =?");
  $sth->execute($var);
  my $rec = $sth->fetchrow_hashref;
  $sth->finish;

  return $rec;
}

#-------------------------------------------------------------

sub getValParamList {
  my ($dbh, $var) = @_;
  my @retArr  = ();
  my @selList = ();
  my $sth =
    $dbh->prepare("select varType,val from opl_preference where var =? ");
  $sth->execute($var);
  if (my ($t, $v) = $sth->fetchrow_array) {
    if ($t =~ m/^checkbox$/g) {
      @selList = split(/,/, $v);
    }
    elsif ($t =~ m/^timeLength$/g) {
      if ($v =~ m/(\d)+([\w])/g) {
        @selList = $2;
      }
    }
    else {
      push @selList, $v;
    }
  }
  if ($var eq 'defCategory') {
    $sth = $dbh->prepare(
"select 'defCategory' var, catid val, catname name,catid listOrder from opl_category order by catid "
    );
  }
  elsif ($var eq 'beginnerSrchLocation' || $var eq 'OWLsrchLocation') {
    $sth = $dbh->prepare(
"select  '$var' var,  sfData val,sfData name  from opl_authCtrl where tag='852' && sfCode='c' "
    );
  }
  else {
    $sth = $dbh->prepare(
      "select * from opl_prefFormParam where var ='$var' order by listOrder");
  }
  $sth->execute();
  my $order=0;
  while (my $rec = $sth->fetchrow_hashref) {
    foreach my $selVal (@selList) {
      if ($selVal eq $rec->{'val'}) {
        $rec->{'selected'} = 1;
        last;
      }
      if(!$rec->{'listOrder'}){
          $rec->{'listOrder'}=$order++;
      }
    }
    push @retArr, $rec;
  }
  return \@retArr;

}

#--------------------------------------------------------------

sub update_var {
  my ($dbh) = @_;
  my ($varName, $varValue, $desc) = ('', '', '');
  $varName = $input->{'var'};
  $desc    = $input->{'description'};
  if ($varName eq 'ILL_Messaging') {
    my $host = ($input->{'val'} eq '0') ? "" : $ENV{'HTTP_HOST'};
    return if (!wsc_updateHostURL($dbh, $host));
  }

  my $sth = $dbh->prepare("select * from opl_preference where var=?");
  $sth->execute($varName);
  if (my $rec = $sth->fetchrow_hashref) {
    my $val     = '';
    my $valShow = '';
    if ($rec->{'varType'} =~ m/^radio$|^select$/g) {
      $val = $input->{'val'};
      if ($varName eq 'defCategory') {
        ($valShow) = $dbh->selectrow_array(
          "select catname from  opl_category where catid=$val");
      }
      else {
        ($valShow) = $dbh->selectrow_array(
"select name from  opl_prefFormParam where var='$varName' && val='$val'"
        );
      }
    }
    elsif ($rec->{'varType'} =~ m/^checkbox$/g) {
      $val = join(",", ($cgi->param('val')));
      $valShow = $val;
      $valShow =~ s/,/, /g;
    }
    else {
      $val     = $input->{'val'};
      $valShow = $input->{'val'};

    }
    $sth = $dbh->prepare(
      "update opl_preference set val=?,valShow=?,description=? where var=?");

    if ($varName eq 'selfcheck') {
      my $acsd_uuid = '';
      my $acsd_conf = '/etc/opals/acsd.conf';
      if ($val == 1) {
        if (-r "$acsd_conf") {
          open ACSD_CONF, "<$acsd_conf";
          while (<ACSD_CONF>) {
            s/^[\s]+|[\s]+$//g;
            if (m/^uuid=([0-9a-f\-]{36})/) {
              $acsd_uuid = $1;
              last;
            }
          }
          close ACSD_CONF;
        }

        return unless $acsd_uuid;
      }

      return unless $sth->execute($acsd_uuid, '', 'ACSD UUID', 'acsd_uuid');
    }
    elsif($varName eq 'currency'){
        my ($code,$symbol) =split(":",$input->{'val'});
            $dbh->do("replace into opl_preference set var='curCode',val=?,hidden=1,gid=1",undef,$code);
            $dbh->do("replace into opl_preference set var='curSymbol',val=?,hidden=1,gid=1",undef,$symbol);

    }

    $sth->execute($val, $valShow, $desc, $varName);
  }
  $sth->finish;
}

#--------------------------------------------------------------
sub getPrefListGroup {
  my $sth_pref = $dbh->prepare(
'select * from opl_preference p inner join opl_prefGroup g on g.id=p.gid where  hidden=0 order by gid,gOrder'
  );
  $sth_pref->execute();

  my @prefMenu = ();
  my $pNum     = -1;
  my $preGid   = 0;
  while (my $p = $sth_pref->fetchrow_hashref) {
    if ($preGid != $p->{'gid'}) {
      my $pref;
      $pNum++;
      $preGid = $p->{'id'};
      my $title = $p->{'title'};
      $pref->{'gid'}          = $preGid;
      $pref->{'title'}        = $title;
      $pref->{'submenu'}      = ();
      $pref->{'submenuCount'} = 0;
      my $submenuPref = ();
      push @prefMenu, $pref;
    }

    my $subPref;

    my $i = @prefMenu[$pNum]->{'submenuCount'};
    $subPref->{'gOrder'}  = $p->{'gOrder'};
    $subPref->{'var'}     = $p->{'var'};
    $subPref->{'val'}     = $p->{'val'};
    $subPref->{'valShow'} = $p->{'valShow'};
    $subPref->{'valShow'} =~ s/,/, /g;
    $subPref->{'hidden'}                = $p->{'hidden'};
    $subPref->{'description'}           = $p->{'description'};
    $subPref->{'opt'}                   = $p->{'opt'};
    @prefMenu[$pNum]->{'submenu'}->[$i] = $subPref;
    @prefMenu[$pNum]->{'submenuCount'} += 1;
  }
  $template->param(prefMenu => \@prefMenu);

  $sth_pref->finish;
}

#--------------------------------------------------------------
__END_OF_FILE:

