#!/usr/bin/perl

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

use JSON::XS;
use FileHandle;

my $ordpos  = shift @ARGV || 1;
my $cqlFile = 'runControllerCols.cql';

my $cql;
my $fh = FileHandle->new( $cqlFile, 'r' );
read $fh, $cql, -s $fh;
$fh->close;

use REST::Neo4p;
eval {
    if ( REST::Neo4p->connect( "http://35.162.82.15:7474", "neo4j", "123123" ) ) {
        my $query = REST::Neo4p::Query->new($cql);
        $query->execute();
        while ( my $result = $query->fetch ) {
            my ( $rc, $contract, $c_start, $c_end, $pos, $term, $t_start, $t_end, $share, $countries, $stores, $txntypes, $label ) = @{$result};
            next if $pos != $ordpos;
            $stores    = stringify($stores);
            $countries = stringify($countries);
            $txntypes  = stringify($txntypes);
            my $sql = (
                qq{
SELECT 
	dsdn.* 
FROM 
	dig_sales_detail_denorm dsdn
WHERE 1  
    AND vendor_id=$label
    AND store_id IN ( $stores )
    AND country_id IN ( $countries )
    AND trans_type_id IN ( $txntypes )
    AND date >= '$t_start'
    AND date <= '$t_end'
        }
            );
            print "$sql\n";
        }
    }
};
if ($@) {
    print $@;
}

sub stringify {
    my $aref = shift;
	my $text; 
	my $i = 1;
    foreach my $n ( sort { $a <=> $b } @{$aref} ) {
		$n = sprintf("%4d",$n);
		if ( $i++ % 24 == 0 ) {
			$text .= "$n,\n";
			$i = 1;
		} else {
			$text .= "$n,";
		}
	}
	$text =~ s/,$//;
	"\n$text\n";
}
