#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

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

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 ($permission, $cookieList, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'util/extdb.tmpl',
            reqPermission   => 'pref_edit',
#            op              => $op,
        }
);

# See User.pm for the list of permissions
if ($permission && $permission->{'pref_edit'}) {
    if ($op eq 'update') {
        my $sth = $dbh->prepare(<<_STH_);
update  opl_extDatabase
set     hidden = ?
where   id = ?
_STH_
        my ($id, $hidden);
        foreach my $c ($cgi->param('edHidden')) {
            $c =~ m/([\d]+):([01])/;
            $id     = $1;
            $hidden = $2;
            $sth->execute($hidden, $id);
        }

        $sth->finish;
    }
}
else { # input for login form
    my @fInput;
    foreach my $c ($cgi->param('edHidden')) {
        push @fInput, {
            name  => 'edHidden',
            value => $c,
        };
    }
    push @fInput, {
        name  => 'op',
        value => 'update',
    };
    $template->param(
        input => \@fInput,
    );
}


 my $scriptName = $ENV{'SCRIPT_NAME'};
   my @extDatabase;
   my $sth = $dbh->prepare(<<_STH_);
select  *
from    opl_extDatabase
where page='searchPage'
order by rank, name, id asc
_STH_
    $sth->execute;
    while (my $es = $sth->fetchrow_hashref) {
        $es->{'VRC'}=1 if($es->{'name'} eq 'VRC');
        $es->{'active'}=1 if($scriptName =~ m/\/vrc$/);
        push @extDatabase, $es;
    }
    $sth->finish;

    $template->param(
        extDatabase => \@extDatabase,
    );


$template->param(hlpUrl     => Opals::Constant->getHlpUrl('extdb') );

tmpl_write($dbh, $cgi, $cookieList, $template);
#$dbh->disconnect();
