#!/usr/bin/perl
#
#
# This will import from the tab delimited spreadsheet produced
# by the GnuLedger-backend 'export' function. This is only
# preliminary stuff. Use at your own risk.
###############################################################


use DBI;

print "mySQL root password: ";
$Pass = <STDIN>;
chomp($Pass);

print "Finance database: ";
$Db = <STDIN>;
chomp($Db);

print "Account: ";
$AccountName = <STDIN>;
chomp($AccountName);

print "Account Type: ";
$AccountType = <STDIN>;
chomp($AccountType);

print "Asset/Liability [A/L]: ";
$astlia = <STDIN>;
lc($astlia);
chomp($astlia);

$dbh = DBI->connect("DBI:mysql:$Db:localhost", 'root', $Pass) or die $DBI::errstr;

#Create our new account:
$Query =  'create table ' .  "$AccountName" . ' (timestmp timestamp, unid integer, tdate date, transnum varchar(100), transfer varchar(100), description varchar (100), credit decimal (9,2), debit decimal (9,2))';
$Cursor = $dbh -> prepare ($Query);
$Cursor -> execute;
$Cursor -> finish;

$Query = "INSERT INTO AccountList (name, parent, atype, astlia) values ('$AccountName', 'None', '$AccountType', '$astlia')";
$Cursor = $dbh -> prepare ($Query);
$Cursor -> execute;
$Cursor -> finish;

print "Input file: ";
$InputFile = <STDIN>;
chomp($InputFile);

open (INPUT, "$InputFile");
while(<INPUT>){
	$CurrentIn = $_;
	chomp($CurrentIn);
	($UNID, $Date, $Transnum, $Transfer,$Description, $Deposit, $Withdrawl) = split (/\t/, $CurrentIn);
	($Mo, $Dy, $Yr) = split(/\//, $Date, 3);
	$Date = "$Yr-$Mo-$Dy";
	if (($Description eq 'Balance Calculation') || ($Description eq '') || ($Description eq 'DESCRIPTION')){
		print "Skipping record...\n";
	} else {
		$Query = "INSERT INTO $AccountName (unid, tdate, transnum, transfer, description, credit, debit) values ('$UNID', '$Date', '$Transnum', '$Transfer', '$Description', '$Deposit', '$Withdrawl')";
		$Cursor = $dbh -> prepare ($Query);
		$Cursor -> execute;
		print "Inserting record \[$Description\] into $AccountName...\n";
		$Cursor -> finish;
	}
}
close(INPUT);
$dbh -> disconnect;
		
