package BookPub::User::Command::Import;

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

use lib '/app/tools/appuser/lib';
use lib '/app/tools/bookpub/lib';
use BookPub::User::ImportForm;

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

use base 'BookPub::Command';

use constant kTemplate => '/app/tools/bookpub/templates/user/import.xsl';

sub cmd      { return "import"; }
sub area     { return "user"; }
sub pageName { return 'Edit 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;

    # Going to just re-use the existing form object.
    #
    my $form = BookPub::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;
