#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2015 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------

package Report::Dynamic::DirectQuery;
use strict;

use lib '/app/tools/common/lib';
use lib '/app/tools/report/lib';
use base 'Report::Dynamic::SingleQuery';

use Common::Client;
use Common::Log;
use File::Temp;

sub _preCreateFiles {
    my ($self) = @_;

    if ( !-d $self->DefaultTempFilePath() ) {
        my $fileDirectory = $self->DefaultTempFilePath();
        File::Path::mkpath($fileDirectory) or die "ERROR: Unable to create path $fileDirectory: $!";
    }

    my $fhUnsorted = File::Temp->new( TEMPLATE => $self->reportID() . "XXXX", DIR => $self->DefaultTempFilePath(), SUFFIX => '.unsorted' );
    binmode( $fhUnsorted, ":utf8" );

    my $directIO = Common::RSApp::GetClientDB()->DirectIO();

    my $columnConfig   = $self->_columns();
    my $itemCollection = $self->_getCollection();

    # Okay, this is super gross, but unless we want to build stuff off of not-DBItems (which at least centralizes our SQL)
    # OR just get the overhead that comes with same, we've got to steal the query from the Common::DB::ItemCollection
    # (and it doesn't seem like we quite want to go down the public accessor route yet either)
    my $sth = Common::RSApp::GetClientDB()->DoCmd( $itemCollection->{_query} );

    $self->_runQuery( $sth, $fhUnsorted );

    $fhUnsorted->close();
    $self->{fhSorted} = File::Temp->new( TEMPLATE => $self->reportID() . "XXXX", DIR => $self->DefaultTempFilePath(), SUFFIX => '.sorted' );
    binmode( $self->{fhSorted}, ":utf8" );

    Common::Log::Print("sorting file start");
    $self->_sort( $fhUnsorted->filename, $self->{fhSorted}->filename );
    Common::Log::Print("sorting file end");
}

sub _nextReportLineData {
    my ($self) = @_;

    while ( my $line = $self->{fhSorted}->getline() ) {
        $line =~ s/\n//g;
        my @lineData = split( "\t", $line );

        if ( $self->parameters()->{Criteria}->Consolidate() eq 'None' ) {
            return \@lineData;
        }

        if ( $self->{_aggData} ) {
            my $i = 0;
            foreach my $col ( @{ $self->_columns() } ) {
                if ( $col->{sortOrder} && $self->{_aggData}->[$i] ne $lineData[$i] ) {
                    my $aggReturn = $self->{_aggData};
                    $self->{_aggData} = \@lineData;
                    return $aggReturn;
                }
                $i++;
            }

            $i = 0;
            foreach my $col ( @{ $self->_columns() } ) {
                if ( $col->{sum} ) {
                    $self->{_aggData}->[$i] += $lineData[$i];
                }
                $i++;
            }
        } else {
            $self->{_aggData} = \@lineData;
        }
    }

    if ( $self->{_aggData} ) {
        my $aggReturn = $self->{_aggData};
        $self->{_aggData} = undef;
        return $aggReturn;
    }
}

sub _sort {
    my ( $self, $unsorted, $sorted ) = @_;

    my $columnConfig = $self->_columns();

    my @sortKeys;
    my $publisherOrPayee = 0;
    my $i = 1;
    foreach my $col (@$columnConfig) {
        $publisherOrPayee = $i if $col->{header}{name} =~ /^(?:publisher|payee)$/i;
        if ( defined( $col->{sortOrder} ) ) {
            $sortKeys[ $col->{sortOrder} ]->{field}   = $i;
            $sortKeys[ $col->{sortOrder} ]->{numeric} = $col->{sortNumeric};
        }
        $i++;
    }

    my $sortSwitch;
    foreach my $key (@sortKeys) {
        my $field = $key->{field};
        $sortSwitch .= "-k$field";
        $sortSwitch .= "n" if $key->{numeric};
        $sortSwitch .= ",$field ";
    }

    $sortSwitch = qq/-k$publisherOrPayee,$publisherOrPayee $sortSwitch/ if $publisherOrPayee;
    my $sort = "nice sort -f -t '\t' -T " . $self->DefaultTempFilePath() . " " . $sortSwitch . $unsorted . " > " . $sorted;

    system($sort);
}

1;
