#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package Common::DB::Item::CommandLog;
use lib '/app/tools/common/lib';
use Common::Log;
use Common::DB::Item;
use Common::DB::ItemCollection;
use Common::Debug;
use Data::Dumper;
use base 'Common::DB::Item';

use constant kTable => 'command_log';
use constant kDB    => Common::DB::Item::kClientDB();

# JPK - Normally I don't go in for these 'swiss army knife' accessors,
# but in this case I'll make an exception.  This table is going to be
# used in a variety of ways, and I don't want to have to have a lot
# of extra code cluttering up both this file and the XMLObjects that will use it.
#

sub Get {
    my ( $class, %args ) = @_;

    Common::Log::Print( "CommandLog::Get args: " . Dumper( \%args ) );

    my $dbo = Common::RSApp::GetClientDB();

    my @selectFields = ('*');

    # Construct 'where' clause
    #
    my @where;
    if ( $args{user_id} ) {
        push @where, "created_by=" . $args{user_id};
    }
    if ( $args{command} ) {

        # Command might be an array.
        #
        if ( 'ARRAY' eq ref( $args{command} ) ) {
            my @subWhere;
            foreach my $c ( @{ $args{command} } ) {
                push @subWhere, $dbo->DBQuote($c);
            }
            push @where, "command_name IN (" . join( ',', @subWhere ) . ") ";
        } else {
            push @where, "command_name=" . $dbo->DBQuote( $args{command} );
        }
    }

    # Any additional modifiers?
    #
    my @groupBy;
    my @orderBy;
    if ( $args{most_recent} ) {
        push @selectFields, 'MAX(date_created)';
        push @groupBy,      'command_name';
        push @groupBy,      'command_id';

        # This '7' stuff is a bit fragile... Basically, I want to order
        # by the MAX(date_created) column. This works, but will break
        # if at some point we add another column to the table.
        #
        push @orderBy, '7 desc';
    }

    my $limit;
    if ( $args{limit} ) {
        $limit = $args{limit};
    }

    # Construct the sql statement
    #
    my $sql = "SELECT " . join( ',', @selectFields ) . " FROM " . kTable;
    if ( scalar @where ) {
        my $whereString = join( " AND ", @where );
        $sql .= " WHERE $whereString";
    }
    if ( scalar @groupBy ) {
        $sql .= ' GROUP BY ' . join( ',', @groupBy );
    }
    if ( scalar @orderBy ) {
        $sql .= ' ORDER BY ' . join( ',', @orderBy );
    }
    if ($limit) {
        $sql .= " LIMIT $limit";
    }
    Common::Log::Print("CommandLog::Get sql:$sql");

    return $class->GetAll($sql);
}

1;
