#! /usr/bin/perl
use Text::CSV_XS;
use utf8;
use Encode;
require './autoeconomy.pm';

binmode STDIN, ':utf8';
binmode STDOUT, ':utf8';

my $csv = Text::CSV_XS->new({ sep_char => "\t", binary => 1 });
my $dbh = autoeconomy::db_connect();
my $num = 0;

my $account = $ARGV[0];

while (<STDIN>) {
	$csv->parse($_);
	my ($accounting_date,$interest_date,$use_date,$reference,$type,$text,$out,$in) = $csv->fields;
	next if ($interest_date eq 'RENTEDATO');

	# Find out if it's there already (FIXME: might need a text+type update?)
	my ($count) = $dbh->selectrow_array('SELECT COUNT(*) AS cnt FROM transaction WHERE reference=?', undef, $reference);
	next if ($count > 0);

	$type = Encode::decode("iso8859-1", $type);
	$text = Encode::decode("iso8859-1", $text);
	$out =~ s/,/./;
	$in =~ s/,/./;
	$out = undef if ($out eq '');
	$in = undef if ($in eq '');
	print "$text\n";

	my $q = $dbh->prepare('INSERT INTO transaction (account,accounting_date,interest_date,use_date,reference,trans_type,text,amount_out,amount_in) VALUES (?,?,?,?,?,?,?,?,?)');
	$q->execute($account,$accounting_date,$interest_date,$use_date,$reference,$type,$text,$out,$in);

	++$num;
}

print "$num records inserted.\n";
