#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package Common::Query;
use strict;
use warnings;

use File::Basename;

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::Client;

use base 'Common::Script';

sub _options {
    {
        file => {
            short       => 'f',
            description => 'File containing SQL query to run (otherwise read from stdin)',
            parameter   => 's'
        },
        ignore_error => {
            short       => 'i',
            description => 'Ignore database errors',
        },
    };
}

sub _init {
    my $self = shift;
    my %args = @_;
    my $fh;

    $self->SUPER::_init(%args);

    my $file = $self->param('file');

    if ($file) {
        open( INFILE, $file )
          || die("Could not open file: $file ($!)");
        $fh = \*INFILE;
    } else {
        $fh = \*STDIN;
    }

    $self->{_sql}          = $self->_getQuery($fh);
    $self->{_ignoreErrors} = $self->param('ignore_error');

    close(INFILE) if ( $args{file} );

    return $self;
}

sub _getQuery {
    my $self = shift;
    my $fh = shift || die;

    my $sql;

    while (<$fh>) {
        $sql .= $_;
    }

    return $sql;
}

sub _runQuery {
    my $self            = shift;
    my $dbo             = Common::RSApp::GetClientDB();
    my $client          = new Common::Client( clientID => Common::RSApp::GetClientID() );
    my $clientID        = $client->ClientID();
    my $clientName      = $client->ClientName();
    my $clientNameClean = $client->ClientNameClean();

    $self->{_clientID}        = $clientID;
    $self->{_clientName}      = $clientName;
    $self->{_clientNameClean} = $clientNameClean;

    $self->debug("Running Query: $self->{_sql}\n");
    my $sth;

    eval { $sth = $dbo->DoCmd( $self->{_sql} ); };

    if ($@) {
        if ( $self->{_ignoreErrors} ) {
            print STDERR "$@\n";
        } else {
            die $@;
        }
    } else {
        while ( my $row = $sth->fetchrow_hashref() ) {
            $self->_printHeader($row);
            $self->_printRow($row);
        }
    }
}

sub _printHeader {
    my $self = shift;
    my $row = shift || die;

    unless ( $self->{_headerOut} ) {
        print "client_id\tclient_name\tclient_name_clean";

        foreach ( keys(%$row) ) {
            print "\t$_";
        }

        print "\n";
        $self->{_headerOut} = 1;
    }
}

sub _printRow {
    my $self = shift;
    my $row = shift || die;

    print "$self->{_clientID}\t$self->{_clientName}\t$self->{_clientNameClean}";

    foreach ( keys(%$row) ) {
        printf( "\t%s", $row->{$_} ? $row->{$_} : "" );
    }

    print "\n";
}

sub _process {
    my $self = shift;
    assert($self);

    $self->_runQuery();
}

1;
