#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package Admin::Help::Command::Show;
use strict;
use warnings;

use lib '/app/tools/admin/lib';
use Admin::Command;
use base 'Admin::Command';

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

sub cmd  { return 'show'; }
sub area { return 'help'; }

# JPK - This might move...
#
use constant kHelpFileBasePath => "/app/tools/admin/templates/help";
use constant kGlobalHelpFile   => "/app/tools/admin/templates/help/help.xsl";

# Example path: kHelpFileBasePath . '/catalog/show.html';

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

    # Need to check for a valid session, even for help files.
    #
    my $response = $self->SUPER::execute();
    return $response if $response;

    my $area            = $self->getParam('a');
    my $originalCommand = $self->getParam('oc');

    my @helpPath;
    push @helpPath, $area;
    push @helpPath, $originalCommand if $originalCommand;

    # So, we're going to first attempt to find the help file that directly
    # corresponds to the specified area and command.
    # - If we can't find that, _OR_ this use doesn't have permission to access
    #   that command, we'll try to find the default help file for the area.
    # - If that doesn't exist, or they can't access the default command, then
    #   just serve the top-level help file.
    #
    my $helpFile;
    while ( !$helpFile && scalar @helpPath ) {
        my $helpArea = $helpPath[0];
        my $helpCmd = $helpPath[1] || 'DEFAULT';

        # !!! The point of this rigamorole is to figure out the _actual_ name of
        # the command - If we're trying to load the help file for the default command,
        # we don't know what that's actually called.
        #
        my $cmdPkg = Admin::App->GetCommandPkg( $area, $helpCmd );
        if ($cmdPkg) {
            eval "require $cmdPkg";

            my $commandObj = $cmdPkg->new();

            if ( $commandObj->hasPermission() ) {
                my $possibleFilePath = kHelpFileBasePath . '/' . $commandObj->area() . '/' . $commandObj->cmd() . '.xsl';

                # Let's be careful and make sure we're looking at a TEXT file...
                #
                if ( -e $possibleFilePath ) {
                    $helpFile = $possibleFilePath;
                    last;
                }
            }
        }

        pop @helpPath;
    }

    if ( !$helpFile ) {

        # Use the global help file.
        $helpFile = kGlobalHelpFile;
    }

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

    return $response;
}

1;
