#!/usr/bin/perl

use Config::General;
use Getopt::Long;
use FindBin qw($Bin);
use lib "$Bin";
use DB::Fundcalc;

use strict;
use warnings;

my $update_name;
my $verbose;
my $result = GetOptions("update-name" => \$update_name,
			"verbose|v" => \$verbose);
unless ($result) {
    print "Usage: $0 [--update-name] [--verbose|-v]\n";
    die;
}

my $schema = DB::Fundcalc->connect('dbi:SQLite:openfund.sqlite');
my $fund_table = $schema->resultset('Fund');
my $price_table = $schema->resultset('Price');

my $no_exists_warnings = 1;
my $output_filename = 1;

my $code;
my $diff;
my $name;
my $net;
my $total = 0;			# old data, such as from 2006, has no total.
my $fund_id;

my $date = join '-', $ARGV[0] =~ m{.*\.funds/([0-9]*)/([0-9]*)/([0-9]*).*};

print "processing $ARGV[0] ...\n" if defined $output_filename;

my $processed = 1;
open FROM, "<$ARGV[0]" or die "$ARGV[0] not found";
while(<FROM>) {
    if (/code\s*([0-9]*)/) {
	my $new_code = $1;
	unless ($processed == 1) {
	    &insert_fund;
	}
	$code = $new_code;
	$processed = 0;
    }
    elsif (/diff\s*(.*)/) {
	$diff = $1;
    }
    elsif (/name\s*(.*)/) {
	$name = $1;
	my $fund = $fund_table->find_or_new({ code => $code });
	if ($fund->in_storage) {
	    if (defined $update_name) {
		if ($name ne $fund->name) {
		    if (defined $fund->alias and $fund->alias ne "") {
			if ($fund->alias !~ /\Q$name\E/) {
			    $fund->alias($fund->alias . "， " . $name);
			    print "Update alias, $name, for $code ",
				$fund->name, " from $date.\n"
				    if defined $verbose;
			}
		    }
		    else {
			$fund->alias($name);
			print "Insert alias, $name, for $code ", $fund->name,
			    " from $date.\n" if defined $verbose;
		    }
		}
		else {
		    print "$code $name already exists.\n"
			unless defined $no_exists_warnings;
		}
	    }
	}
	else {
	    $fund->code($code);
	    $fund->name($name);
	    print "Insert $code $name\n" if defined $verbose;
	}
	$fund->insert_or_update;
	$fund_id = $fund->id;
    }
    elsif (/net\s*(.*)/) {
	$net = $1;
    }
    elsif (/total\s*(.*)/) {
	$total = $1;
    }
}
&insert_fund unless $processed == 1;
close FROM;

sub insert_fund {
    my $price = $price_table->find_or_new({ fund_id => $fund_id,
					    date => $date });
    if ($price->in_storage) {
	print "$code\'s price ($net) already exists.\n"
	    unless defined $no_exists_warnings;
    }
    else {
	$price->fund_id($fund_id);
	$price->net($net);
	$price->total($total);
	$price->diff($diff);
	$price->date($date);
	print "Insert price for $name.  Net: $net, Total: $total, Diff: $diff, Date:$date\n" if defined $verbose;
    }
    $price->insert_or_update;
}
