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

use strict;
use warnings;
use Data::Dumper;

use lib '/app/tools/rps/lib';
use RPS::ArtistContract::ContractTermSourceWithRateType;
use RPS::DB::Item::ContractTermSource;

use Common::FormObject;
use base 'Common::FormObject';


sub _init
{
	my ($self, %args) = @_;

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

    $self->{ContractTermSource} = [];

	my $collection = RPS::DB::Item::ContractTermSource->GetAll();
	while ( my $row = $collection->next())
	{
		my $obj = RPS::ArtistContract::ContractTermSourceWithRateType->new(_dbItem => $row);

		if( $row->parent_contract_term_source_id ) {
		    $nodes{$row->parent_contract_term_source_id} = () unless( $nodes{$row->parent_contract_term_source_id} );
		    push( @{$nodes{$row->parent_contract_term_source_id}}, $obj );
		} else {
		    $nodes{0} = () unless( $nodes{0} );
			push( @{$nodes{0}}, $obj );
		}
	}


	#die Dumper \%nodes;

    # Add the ALL Group Item
	my $item = $self->_findItem( 1, $nodes{0} );
	push( @{$self->{ContractTermSource}}, $item ) if( $item );

	# Add "All Digital" and "All Physical" group items
	foreach my $index ( sort keys %nodes ) {
		# Skip any items in the first two levels.  i.e. "All" and "All Digital"
		next if ( $index == 0 || $index == 1 );

		$item = undef;
		foreach my $menuItem ( @{$nodes{$index}} ) {

			# Add the group header item
			unless( $item ) {
			    $item = $self->_findItem( $menuItem->{ParentContractTermSourceID}, $nodes{1} );
		        push( @{$self->{ContractTermSource}}, $item );
			}

		    push( @{$self->{ContractTermSource}}, $menuItem );
		}
	}

	# Add All non-group level 1 items, MASTER and SYNC
	foreach my $menuItem ( @{$nodes{1}} ) {
		next if( $menuItem->{ContractTermSourceID} <= 3 );
		push( @{$self->{ContractTermSource}}, $menuItem );
	}

	return $self;
}

sub _findItem {
	my $self = shift;
	my $id = shift || return;
	my $nodes = shift || return;

	foreach my $node ( @$nodes ) {
		my $nodeID = $node->{ContractTermSourceID};
		return $node if( $nodeID == $id );
	}

	return;
}


###
1;#
###
