package AppUser::User::Command::Import;

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

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

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

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

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

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

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 $form = AppUser::User::ImportForm->new( accessLevel => $self->_getUser()->AccessLevel() );

    # Importing a user is a multi step process.
    #
    # 1. Enter the email address of the user you want to import from another client
    # 2. Validate the email address and verify that permissions allow the import to occur
    #
    # are we submitting anything yet?
    #
    if ( $self->getParam("formSubmit") && $form->assignCGIParams( 'Form', $self->getParams() ) ) {
        if ( $form->Import() ) {
            if ( $form->validateImport() ) {
                $form->save();
                $self->addMessageXML( type => "success", code => Common::FormObject::kImportSuccess );
            } else {
                $form->setError(Common::FormObject::kErrFormSubmit);
                $self->addMessageXML( type => "error", code => Common::FormObject::kErrFormSubmit );
            }
        } elsif ( $form->Email() ) {
            if ( $form->validateEmail() ) {

                # send success msg
                $self->addMessageXML( type => "success", code => Common::FormObject::kImportEmailFound );
            } else {
                $form->setError(Common::FormObject::kErrFormSubmit);
                $self->addMessageXML( type => "error", code => Common::FormObject::kErrFormSubmit );
            }
        }
    } else {

        # $form->setError(Common::FormObject::kErrFormSubmit);
        # $self->addMessageXML(type => "error", code => Common::FormObject::kErrFormSubmit);
    }

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

    return $response;
}

1;
