#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long;

my $split = 0;
my @DB_OTHER = ();
my $db_value = "me";


sub get_records {
    my ($filename) = @_;
    my @DOCUMENTS;
    local $/="\n\n";

    open (IN, "iconv -f CP437 -t UTF-8 $filename | dos2unix |") or die;
    my $header = <IN>;
    my ($_, $version, $db_key, $n, $m, $s, $d, $k) = split (" ", $header);
    
    while (<IN>) {

        # RECORD START
        my %document = ();
        for (split ("\n", $_)) {
            if (/^\\(\S+)\s+(.*)/) {
                next if $2 eq "";
                my @VALUES = split "\\s*[;-]\\s*", $2;
                $document{$1} = \@VALUES;
            }
        }
        # RECORD END
        push (@DOCUMENTS, \%document) if keys %document;
    }
    close IN;

    format_document ($db_key, $_) for (@DOCUMENTS);
}

sub join_values {
   my ($list) = @_;
   my $string =  join ", ", map {"\"" . $_ . "\""} @$list;
   
   $string = "[ $string ]" if ($#$list > 0);
   return $string;
}

sub format_document {
    my ($db_key, $document) =  @_;

    # multiple entries for value ??
    if ($#{$document->{$db_value}} > 0 && $split) {
       my @LIST = ();
       for my $value (@{$document->{$db_value}}) {
          push @LIST, '"' . $value .'"';
       }
       $document->{$db_value} = \@LIST;
    }
    else {
       $document->{$db_value} = [ join_values ($document->{$db_value}) ];
    }
    {
       for my $value (@{$document->{$db_value}}) {
          print '{ "key" : "' . $$document{$db_key}[0] . '",';
          print ' "value" : ' . $value;

          my @PARTS = ();
          for my $key (@DB_OTHER) {
             my $multi_value = ($#{$document->{$key}} > 0);
             print ", \"$key\" : ";
             print join_values ($document->{$key});
          }
          print " }\n";
       }
    }
}

sub usage {
    print "Usage: convert [OPTION...] FILE\n\n";    
    print "  --split            split value\n";
    print "  --db-value=DBKEY   value key\n";
    print "  --db-other=DBKEY   other keys\n";
    print "  --db-other=DBKEY   other keys\n";
    print "\n";
    print "import to mongodb with:\n";
    print "  mongoimport --db DB --collection COLLECTION --file FILE>\n";
    exit 1;
}

sub main {
   GetOptions ("split!" => \$split,
               "db-value=s" => \$db_value,
               "db-other=s@" => \@DB_OTHER,
            );

   usage if ($#ARGV != 0);

   get_records ($ARGV[0]);
}

main ();
   


