#!/usr/bin/perl

use constant 'DBDIR' => '/var/app/orchard/database';
use constant 'BLKSZ' => 24000;

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';

use Git;
use JSON::XS;
use FileHandle;
use Text::CSV::Easy(qw/csv_build csv_parse/);
use Getopt::Long::Descriptive(qw/describe_options/);

use lib '/var/app/orchard/collab/jgetter/perllib';
use Orchard::Session;
use Orchard::RunCommand;
use Orchard::YamlConfig;
use Orchard::DB::Connect;

my ( $opt, $usage ) = describe_options(
    '%c %o <some-arg>',
    [ 'file|f=s'  => 'File to run mvn commands with',     { 'requied' => 1 } ],
    [ 'cols|c=i'  => 'Number cols for result default 12', { 'default' => 12 } ],
    [ 'sql|s=s'   => 'SQL at beg of in clause' ],
    [ 'insert|i'  => 'Make an insert clause' ],
    [ 'bsize|b=i' => 'Blocksize override' ],
    [ 'help|?|h'  => "print usage message and exit" ]
);

if ( $opt->help ) {
    print $usage->text . "\n";
    exit;
}

my ( $l, $b ) = ( -1, 0 );

my $data;
my $blocks;

my $bsize = $opt->bsize || BLKSZ;

my $fh = FileHandle->new( $opt->file, 'r' );
while (<$fh>) {
    chomp;
    push @{$data}, $_;
    $b++ if ++$l % $bsize == 0;
    push @{ $blocks->{$b} }, $_;
}
$fh->close;

my $beg;
if ( $opt->sql ) {
    $beg = $opt->sql;
    $beg .= "\n(" if not $opt->insert;
} else {
    $beg = '(';
}

if ( $opt->insert ) {
    foreach my $b ( keys %{$blocks} ) {
        my $output = content( $blocks->{$b} );
        print "$beg\n$output";
    }
} else {
    my $output = content($data);
    print "$beg\n$output";
}

sub content {
    my $data = shift;
    my $content;

    my $i = 0;
    my $subset;
    foreach my $col ( @{$data} ) {
        push @{$subset}, $col;
        $i++;
        if ( $i % $opt->cols == 0 and $i != scalar @{$data} ) {
            my $output;
            if ( $opt->insert ) {
                $output = join ",", map { "($_)" } @{$subset};
            } else {
                $output = join ",", @{$subset};
            }
            $content .= "$output,\n";
            undef $subset;
        }
    }
    $content .= ending($subset);
	$content;
}

sub ending {
    my $subset = shift;
    my $end;
    if ( $opt->insert ) {
        $end = join ",", map { "($_)" } @{$subset};
    } else {
        $end = join ",", @{$subset};
        $end .= ")";
    }
    "$end;\n";
}
