use strict;
use warnings;

use DBI;
use  Benchmark qw(:all) ;

die("Usage: $0 input-file.txt\n") if (@ARGV == 0) ;

my $debug=1;
my $database = "game.db";

unlink($database);

# my $database = ":memory:";
# メモリ上のデータベースへ接続
my $dbh = DBI->connect("dbi:SQLite:dbname=$database");

# テーブルの作成
my $create_char = 
"create table characters (" .
       "char_id," .
       "name," .
       "hp," .
       "money" .
");";
$dbh->do($create_char);

my $create_item = 
"create table items (" .
       "item_id," .
       "name," .
       "price" .
");";
$dbh->do($create_item);

my $create_char_item1 = 
"create table char_item (" .
       "char_id," .
       "item_id" .
");";
$dbh->do($create_char_item1);

# インデックスの作成
my $create_index = 
"create index icharacters on characters (" .
       "char_id" .
");";
$dbh->do($create_index);

my $create_index1 = 
"create index iitems on items (" .
       "item_id" .
");";

$dbh->do($create_index1);

my $create_index2 = 
"create index ichar_item on char_item (" .
       "char_id" .
       ",item_id" .
");";
$dbh->do($create_index2);


# insert文の実行
my $char_id = 1;
my $item_id = 1;

# add quote
# (a,b,c) => "'a','b','c'"
sub quote {
    my (@cols) = @_;
    my ($out) = join("','",@cols);
    return "'$out'";
}

while(<>) {
    next if (/^#/);
    chop;
    my @cols = split(/\s*,\s*/,$_);

    my $kind = shift(@cols);
    if ($kind =~ /^character/) {
	my $cmd = 
"insert into characters (char_id, name,hp, money ) values ('$char_id',".
    quote(@cols).
");";
	$char_id++;
	print $cmd,"\n"  if ($debug) ;
        $dbh->do($cmd);
    } elsif ($kind =~ /^item/) {
	my $cmd = 
"insert into items (item_id, name, price) values ('$item_id',".
    quote(@cols).
");";
	$item_id++;
	print $cmd,"\n"  if ($debug) ;
	$dbh->do($cmd);
    } elsif ($kind =~ /^charitem/) {
	my $cmd = 
"insert into char_item (char_id, item_id) values (".
    quote(@cols).
");";
	print $cmd,"\n"  if ($debug) ;
	$dbh->do($cmd);
    }
}

# データベースの切断
$dbh->disconnect;



