#!/usr/bin/perl 
use lib("/www/opals/module");
use strict;
use Getopt::Std;
use Opals::Constant; 
use Date::Calc::Object qw(
    :all
);
use Digest::SHA qw(
    sha1_hex
    sha512_hex
);

use POSIX qw(
    ceil
    floor
);

use Time::localtime;


use Business::ISBN;
use Opals::Marc::Record;
use MARC::Record;
use MARC::Field;
use MARC::File::XML;

my %options = ();
getopts("c:f:",\%options);
my $configFile = $options{c};
my $lexileFile = $options{f};
if (!$configFile || ! -f $configFile || !$lexileFile || ! -f $lexileFile) {
    print "Usage: $0 -c CONFIG_FILE -f LEXILE_FILE \n";
    exit 1;
}

use DBI;
my $config = loadConfig($configFile);
my $dbh = makeConnection($config);

my $zRoot   =   $config->{'zRoot'};
my $zPort   =   $config->{'zPort'};
my $zDatabase = $config->{'zDatabase'};


open LEXILE ,"<$lexileFile";
my $line="";
my $count=0;
my $fieldIndex={isbn13=>{text=>'ISBN13',      index=>-1},
                code  =>{text=>'Lexile Code', index=>-1},
                lexile=>{text=>'Lexile',      index=>-1}
               };
while (<LEXILE>){
    $line=$_;
    my @headers =split("\t",$line);
    for(my $i=0; $i<scalar(@headers);$i++){
        foreach my $f(keys %$fieldIndex){
            my $h=$fieldIndex->{$f}->{'text'};
            if(@headers[$i] =~ m/^$h$/gi){
                $fieldIndex->{$f}->{'index'}=$i;
            }
        }
    }
    last;
};

my ($i,$j,$k)=($fieldIndex->{'isbn13'}->{'index'},$fieldIndex->{'code'}->{'index'},$fieldIndex->{'lexile'}->{'index'});

if($i<0 || $j<0 || $k<0){
    print "Invalid lexile file; it must be a CSV file and has at least the following 3 fields:\n";
    print "\tISBN13\n\tLexile Code\n\tLexile\n";
    exit 1;
}
my $sth=$dbh->prepare("replace into lexile(isbn13,code,lexile) values(?,?,?)");
#$dbh->do("truncate table lexile");
while (<LEXILE>){
    $line=$_;
    my @data =split("\t",$line);
   
    next if(scalar(@data) <$i || scalar(@data) <$j || scalar(@data) <$k);

    my($isbn13,$code,$lexile)=(@data[$i],@data[$j],@data[$k]);
    $sth->execute(@data[$i],@data[$j],@data[$k]);
}
$sth->finish;
############################################################
sub makeConnection {
    my ($config) = @_;
    if (!$config) {
        return;
    }
    my ($db_driver, $db_name, $db_host, $db_port, $db_user, $db_password);

    $db_driver   = $config->{'db_driver'} || 'mysql';
    $db_name     = $config->{'db_name'};
    $db_host     = $config->{'db_host'};
    $db_port     = $config->{'db_port'}   || '3306';
    $db_user     = $config->{'db_user'};
    $db_password = $config->{'db_password'};

    my $dsn = "dbi:$db_driver:$db_name:$db_host:$db_port";

    return DBI->connect($dsn, $db_user, $db_password);
}
############################################################


sub loadConfig {
    my ($configFile) = @_;
#    print "Enter the config filename of Opals: ";
#    $configFile = <STDIN>;
    my $config = {};

    open CONF, $configFile || die "Cannot open file $configFile";
    while (<CONF>) {
        chomp;
        s/#.*//;                # remove comments
        next if /^\s*$/;        # ignore blank lines

        if (/^\s*(\w+)\s*=\s*(.*?)\s*$/) {
            $config->{$1} = $2;
        }
    }
    close CONF;

    return $config;
} 

$| = 1;

