#!/usr/bin/perl

# use module
use XML::Simple;
use Data::Dumper;
use Term::ProgressBar;
use DBI;
if ($#ARGV != 1) {
    print "usage: mamexml2db <infile.xml> <outfile.db>\n";
    exit;
}
print "mamexml2db v0.1\n";
#create/open file, and delete old content
$dbh = DBI->connect( "dbi:SQLite:$ARGV[1]" ) || die "Cannot connect: $DBI::errstr";
if (!($dbh -> do ("delete from mame")))
{
    print "Database is empty, creating..";
    $sqlstring=" 
    CREATE TABLE mame (
      name,
      description [TEXT],
      cloneof [TEXT],
      romof [TEXT],
      year [INTEGER],
      manufacturer [TEXT],
      buttons [INTEGER],
      players [INTEGER],
      vtype [TEXT],
      vwidth [INTEGER],
      vheight [INTEGER],
      vrotate [INTEGER],
      vrefresh [REAL])   ";
    $dbh -> do( $sqlstring) || die "Failed creation: $DBI::errstr";
}

# create object
$xml = new XML::Simple (KeyAttr=>['game']);
# read XML file
print "Parsing the XML file, hold on..\n";
$data = $xml->XMLin($ARGV[0]);
print "Done parsing XML\n";
#loop through gamelist
$count=0;

foreach $e (@{$data->{game}}) {
    $count++;
}
print "populating database with $count games\n";
my $progress = Term::ProgressBar->new({
    count=>$count,
});
$progress->minor(0);
$updatecount=0;

foreach $e (@{$data->{game}})
{

    $input=$e->{input};
    $display=$e->{display};
    if (ref($e->{'display'}) eq 'ARRAY') { 
	$display=$e->{display}[0];
#	print $e->{name}," - ", $e->{display}[0], "\n";
    }

    $sqlstring=("INSERT INTO mame (name,year,manufacturer,description,cloneof,romof,buttons,players,vtype,vwidth,vheight,vrefresh,vrotate ) VALUES (
        \"$e->{name}\",
        '$e->{year}',
        \"$e->{manufacturer}\",
        \"$e->{description}\",
        '$e->{cloneof}',
        '$e->{romof}',
        '$input->{buttons}',
        '$input->{players}',
        '$display->{type}',
        '$display->{width}',
        '$display->{height}',
        '$display->{refresh}',
        '$display->{rotate}'
        )");
    $dbh -> do( $sqlstring);
    $count--;
    $updatecount++;
    if($updatecount=900) {
        $progress->update($count);
        $updatecount=0;
    }
}
$dbh->disconnect;
