#!/usr/bin/perl

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

use JSON::XS;
use FileHandle;
use File::Basename;
use Parallel::ForkManager;
use Text::CSV::Easy(qw/csv_build csv_parse/);

use lib '/app/tools/common/lib';
use Common::Session;

use lib '/app/tools/stats/lib';
use Stats::Redshift::FileSummary;
use Stats::Redshift::SaleStage::RPS;
use Stats::Redshift::SaleStage::DTMV;

my ( $opt, $usage ) = clopt(
    [ 'help|?|h'      => "Print usage message and exit", { 'implies'  => { 'database' => 1 } } ],
    [ 'database|d=s'  => 'Client to export - required',  { 'required' => 1 } ],
    [ 'chunksize|c=s' => 'Chunk of rows to query' ],
    [ 'nocompress|n'  => 'Do not compress results files' ],
    [ 'parallel|p=i'  => 'Parallel threads to query - default 0', { 'default' => 0 } ]
);
if ( $opt->help ) {
    logMessage( 'info', $usage->text, 'options' );
    exit 1;
}

my $stats;
if ( $opt->database =~ m/^C_/ ) {
    $stats = Stats::Redshift::SaleStage::RPS->new( $opt->database );
} else {
    $stats = Stats::Redshift::SaleStage::DTMV->new( $opt->database );
}

my $exp = $stats->exporter;
$exp->chunksize( $opt->chunksize ) if defined $opt->chunksize;
$exp->parallel( $opt->parallel );
$exp->compress(0) if $opt->nocompress;
$exp->directory( $stats->directory );
$exp->directory->table('sale');

my $files    = $exp->export_table( 'sale', $stats->exportsql );
my $manifest = $stats->create_manifest($files);
$stats->send_to_s3;
$stats->load_redshift;
