package Support::User::Command::Login;

use strict;
use warnings;
use URI::Escape;

use lib '/app/tools/support/lib';
use Support::User::LoginForm;

#use AppUser::Login::LoginForm;

# this is a special command, there's no check for session or permission
# so we'll just derive from the basic RSApache::Command base class and define
# our "app" while other "user" Commands will derive from AppUser::Command
#
use lib '/app/tools/appuser/lib';
use base 'AppUser::Login::Command::Login';

sub cmd  { return "login"; }
sub area { return "login"; }
sub app  { return "support"; }

use constant kTemplate => '/app/tools/support/templates/login.xsl';

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

    my $form;
    my $response;
    my $redirect = uri_unescape( $self->getParam("redirect") );
    my $session  = RSApache::RSWebApp::GetSession();

    if ( $session->IsValid() && Common::RSApp::GetClientID > 0 ) {
        $response = RSApache::Response::Redirect->new("/");
    } else {
        $form = Support::User::LoginForm->new( redirect => $redirect );
        if ( $self->getParam('submit') ) {
            if ( $form->assignCGIParams( 'Form', $self->getParams() ) && $form->validate() ) {
                $response = $form->acceptLogin();
            } else {
                $form->setError(Common::FormObject::kErrFormSubmit);
                $self->addMessageXML( type => "error", code => Common::FormObject::kErrFormSubmit );

                use Data::Dumper;
                Common::Log::Debug( Dumper($form) );
            }
        }
    }

    if ( !$response ) {
        $self->{xml}{Form} = $form;
        $response = RSApache::Response::XSLT->new( $self->{xml}, kTemplate );
    }

    return $response;
}

1;
