#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Mechanical::UK::Command::List;
use strict;
use warnings;
use Data::Dumper;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::UKMechanicalRun;
use RPS::Mechanical::UK::UKMechanicalRun;
use RPS::Payor::PayorList;
use RPS::RoyaltyRun::RoyaltyRunStatusList;
use RPS::Pagination;
use RPS::Command;
use base 'RPS::Command';

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

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

use constant kTemplate => "/app/tools/rps/templates/uk_mech/list.xsl";

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

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

    my $payor    = $self->getParam("payor");
    my $status   = $self->getParam("status");
    my $page     = $self->getParam("page") || 1;
    my $pageSize = $self->getParam("pageSize") || 25;

    my $collection = RPS::DB::Item::UKMechanicalRun->GetAllFiltered( payor => $payor, status => $status );

    $collection->setPagination( pageIndex => $page, pageSize => $pageSize );

    $self->{xml}{Pagination} = RPS::Pagination->new(
        total     => $collection->totalSize(),
        recordNum => $collection->{_record},
        pageSize  => $pageSize
    );

    $self->{xml}{UKMechanicalRunList} = $self->_getRunList($collection);

    my $payorIDs = RPS::DB::Item::UKMechanicalRun->GetPayorIDs();

    if ( scalar @$payorIDs ) {
        $self->{xml}{PayorList} = RPS::Payor::PayorList->new( ids => $payorIDs );
    }

    $self->{xml}{StatusList} = RPS::RoyaltyRun::RoyaltyRunStatusList->new( ukMechanical => 1 );

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

sub _getRoyaltyRunStatusList {
    return RPS::RoyaltyRun::RoyaltyRunStatusList->new( ukMechanical => 1 );
}

sub _getRunList {
    my ( $self, $collection ) = @_;

    my $list->{UKMechanicalRun} = [];

    if ($collection) {
        while ( $collection->hasNext() ) {
            my $obj = $collection->next();
            push @{ $list->{UKMechanicalRun} }, RPS::Mechanical::UK::UKMechanicalRun->new( _dbItem => $obj, loadSubs => 0 );
        }
    }

    return $list;
}

1;
