#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Label::Command::List;

use strict;
use warnings;

use lib '/app/tools/common/lib';

use lib '/app/tools/rps/lib';
use RPS::Command;
use RPS::DB::Item::Label;
use RPS::Label::LabelWithUsers;
use RPS::Label::UserList;

use base 'RPS::Command';

use lib '/app/tools/common/lib';
use RSApache::Response::XSLT;

sub cmd  { return 'list'; }
sub area { return 'label'; }

use constant kTemplate => "/app/tools/rps/templates/label/index.xsl";

# These constants will be used to filter the list returned to the UI.
# If we end up letting the database do all the work, then these might move
# into the appropriate DB::Item interface.  But for now, I'll just grab
# all the labels and apply the filter here as I iterate over the collection.
#
use constant kAllLabels    => 0;
use constant kWithUsers    => 1;
use constant kWithoutUsers => 2;

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

    my $response = $self->SUPER::execute();
    return $response if $response;

    my %getArgs;

    my $searchCollection = RPS::DB::Item::Label->GetAll();
    my $filterFlag       = $self->getParam('filterBy');

    while ( $searchCollection->hasNext() ) {
        my $obj = $searchCollection->next();

        # JPK - Yes, it's rather gross to have to instantiate a full-blown XML Object, then
        # throw it away.  But the table that maps user ids to label id lives in a DIFFERENT DATABASE
        # from the client's Label table.   This means that I can't just do a joined query.
        #
        my $label = RPS::Label::LabelWithUsers->new( _dbItem => $obj );
        if (   !$filterFlag
            || ( kWithUsers == $filterFlag && $label->UserCount() > 0 )
            || ( kWithoutUsers == $filterFlag && $label->UserCount() == 0 ) ) {
            push @{ $self->{xml}{Label} }, $label;
        }
    }

    # LabelWithUsers just contains an array of user ids.
    # To provide the actual list of user names, we'll need a UserList
    #
    $self->{xml}{UserList} = RPS::Label::UserList->new( all => 1 );

    $response = RSApache::Response::XSLT->new( $self->{xml}, kTemplate );
    return $response;
}

1;
