#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package Admin::Permission::PermissionList;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::DB::Item::Permission;

use lib '/app/tools/admin/lib';
use Admin::Permission::Permission;
use Admin::Permission::AccessLevel;

use lib '/app/tools/rps/lib';
use Common::FormObject;
use base 'Common::FormObject';

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

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

    my $app      = $args{app};
    my $area     = $args{area};
    my $cmd      = $args{command};
    my $level    = $args{accessLevel};
    my $skipFlag = $args{skipAdmin};

    $self->{Permission} = [];

    # jpk - yes, I could just pass the args straight through...
    # I prefer to de-reference them, just so everybody is clear
    # about what arguments are being used...
    #
    my $collection = Common::DB::Item::Permission::GetPermissions( app => $app, area => $area, command => $cmd, accessLevel => $level );

    while ( $collection->hasNext() ) {
        my $obj = $collection->next();
        next if ( $skipFlag && 1 == $obj->access_level_id );
        push @{ $self->{Permission} }, Admin::Permission::Permission->new( _dbItem => $obj );
    }

    return $self;
}

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

    my $valid = 1;
    foreach my $permission ( @{ $self->{Permission} } ) {
        if ( !$permission->validate() ) {
            $valid = 0;
        }
    }

    return $valid;
}

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

    foreach my $permission ( @{ $self->{Permission} } ) {
        $permission->save();
    }
}

sub _propertyIsEditable {
    my ( $self, $propertyName ) = @_;

    if ( $propertyName eq 'Permission' ) {
        return 1;
    }
    return 0;
}

sub _listProperties {
    return { Permission => 1 };
}

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

    return $self->{Permission};
}

# This is the special sort of list accessor.
#
sub Permission {
    my ( $self, $index, $methodAddressList, $newValue ) = @_;

    if ( 0 == scalar @$methodAddressList ) {
        if ( defined $newValue ) {
            $self->{Permission}[$index] = $newValue;
        }
        return 1;
    }

    # May need to dynamically add objects to the list...
    #
    if ( !defined $self->{Permission}[$index] ) {
        $self->{Permission}[$index] = Admin::Permission::Permission->new();
    }

    return $self->{Permission}[$index]->_accessProperty( $methodAddressList, $newValue );
}

1;

