#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package AppUser::User::Command::LoginAs;

use lib '/app/tools/common/lib';
use RSApache::RSWebApp;
use RSApache::Response::Redirect;

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

use lib '/app/tools/rps/lib';
use RPS::Message;
use RPS::Command;
use base 'RPS::Command';

sub cmd  { return "loginas"; }
sub area { return "user"; }

use constant kTemplate => '/app/tools/appuser/templates/user/index.xsl';

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

    # Give any inherited methods the first crack at this.
    # (This checks for login and basic access permissions).
    #
    my $response = $self->SUPER::execute();
    return $response if $response;

    my $loginAsUserID = $self->getParam('UserID');
    my $loginAsUser = AppUser::User::User->new( userID => $loginAsUserID, loadSubs => 0 );

    if ( !$loginAsUserID || !$loginAsUser ) {
        my $errMsg = RPS::Message->new( type => "error", code => Common::FormObject::kFieldInvalid );
        my $command = AppUser::User::Command::Search->new( msg => $errMsg->toString );
        my $redirectResponse = RSApache::Response::Redirect->new( $command->getRedirect() );
        return $redirectResponse;
    }

    my $currentUserID = Common::RSApp::GetMasterUserID();
    my $currentUser = AppUser::User::User->new( userID => $currentUserID, loadSubs => 0 );

    if ( $currentUser->AccessLevel > $loginAsUser->AccessLevel ) {
        my $errMsg = RPS::Message->new( type => "error", code => Common::FormObject::kFieldInvalid );
        my $command = AppUser::User::Command::Search->new( msg => $errMsg->toString );
        my $redirectResponse = RSApache::Response::Redirect->new( $command->getRedirect() );
        return $redirectResponse;
    }

    my $session = RSApache::RSWebApp::GetSession();
    $session->CreateAs( master_user => $currentUser, active_user => $loginAsUser );
    $response = RSApache::Response::Redirect->new("/");

    return $response;
}

1;

