#------------------------------------------------------------
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package Common::LandingPage::Module;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Permission;
use Common::Log;
use Common::Assert;

use lib '/app/tools/appuser/lib';
use AppUser::User::User;

use base 'Common::FormObject';

use overload ( '<=>' => 'compare' );

# currently the only permission check we make is with related commands
sub _canView {
    return shift->_canViewRelatedCommands(@_);
}

sub _canViewRelatedCommands {
    my $self = shift;

    # If we don't have any related commands we default to "can view"
    my $commands = $self->relatedCommands() || return 1;

    # Can't check permission if our access level isn't defined
    return unless ( $self->{_accessLevel} );

    $commands = [$commands] unless ( ref($commands) eq 'ARRAY' );

    my $accessLevel = $self->{_accessLevel};
    my $permission  = Common::Permission->new($accessLevel);

    foreach my $command (@$commands) {
        my ( $app, $area, $cmd ) = $self->_parseCommand($command);

        return 1 if ( $permission->canAccess( $app, $area, $cmd, $accessLevel ) );
    }

    return;
}

sub _parseCommand {
    my $self    = shift;
    my $command = shift;

    my ( $app, $area, $cmd ) = split( /\//, $command );

    unless ( $app && $area && $cmd ) {
        die "Failed to parse app/area/command: $app, $area, $cmd";
    }

    return ( $app, $area, $cmd );
}

# This is a list of commands that are assoiated to this module.  If they can read
# any of the commands then we assume they can view the module.
sub relatedCommands { }

sub compare {
    my ( $first, $second ) = @_;

    unless ( UNIVERSAL::isa( $second, 'Common::LandingPage::Module' ) ) {
        die "Can only compare two Common::LandingPage::Module objects, not " . ref($second);
    }

    return $first->DisplayOrder() <=> $second->DisplayOrder();
}

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

    $self->_initProperties();

    my $userID = Common::RSApp::GetActiveUserID();
    $self->{_user} = AppUser::User::User->new( userID => $userID, loadSubs => 0 );

    $self->{_accessLevel} = $self->{_user}->AccessLevel() if ( $self->{_user} );

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

sub _initProperties {
    my $self = shift;

    $self->{DisplayOrder} = $self->DisplayOrder();
    $self->{Stylesheet}   = $self->Stylesheet();
    $self->{Template}     = $self->Template();
    $self->{Title}        = $self->Title();
    $self->{Class}        = $self->Class();
    $self->{Module}       = ref($self);

    return $self;
}

sub DisplayOrder   { die "Must be overloaded" }
sub BodyTemplate   { die "Must be overloaded" }
sub HeaderTemplate { }
sub Title          { die "Must be overloaded" }
sub Class          { die "Must be overloaded" }

###
1;    #
###
