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

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 Common::FormHash;
use base 'Common::FormHash';

sub _tagName {
    return 'Permission';
}

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

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

    # Make note of whether we want to skip admin users here - we'll check this later
    # when adding items to the hash.
    #
    $self->{_skipAdminFlag} = $args{skipAdmin};

    $self->{_sortBy} = $args{sortBy};

    my $collection = Common::DB::Item::Permission->GetPermissions( app => $app, area => $area, command => $cmd, accessLevel => $level );

    return $collection;
}

# So, this is supposed to be the method invoked on the items in the collection that represents the
# key.  For this particular class, we don't have a single unique key field - rather, we use a compound
# key.  So, I will need to add a special method to the Permission object to encapsulate that.
#
sub _keyMethodName {
    return 'Key';
}

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

    return Admin::Permission::Permission->new();
}

sub _getObjectFromDBItem {
    my ( $self, $dbItem ) = @_;

    return Admin::Permission::Permission->new( _dbItem => $dbItem );
}

sub _addObject {
    my ( $self, $object ) = @_;

    if ( $self->{_skipAdminFlag} && 1 == $object->AccessLevelID() ) {
        return;
    }

    $self->SUPER::_addObject($object);
}

# Overriding inherited method to return keys in sorted order
#
sub getKeys {
    my ($self) = @_;

    if ( $self->{_sortBy} ) {
        return $self->getKeysSortedByColumn( $self->{_sortBy} );
    }

    my @keys = sort keys %{ $self->{Permission} };

    return \@keys;
}

sub getKeysSortedByColumn {
    my ( $self, $sortColumn ) = @_;

    # Columns are 0-based.  We actually won't end up here if $sortColumn = 0...
    # Which is fine, since that is the default sort order anyway.
    #

    my @sortOrder;
    push @sortOrder, $sortColumn;
    push @sortOrder, 0 unless 0 == $sortColumn;
    push @sortOrder, 1 unless 1 == $sortColumn;
    push @sortOrder, 2 unless 2 == $sortColumn;
    push @sortOrder, 3 unless 3 == $sortColumn;

    my @keys = sort {
        my @key1Bits = split( /\./, $a );
        my @key2Bits = split( /\./, $b );

        foreach my $col (@sortOrder) {
            my $result = $key1Bits[$col] cmp $key2Bits[$col];
            return $result unless 0 == $result;
        }

        return 0;
    } keys %{ $self->{Permission} };

    return \@keys;
}

1;

