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

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

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

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

use POSIX;

sub cmd  { return "changepw"; }
sub area { return "user"; }
sub pageName { return 'Change Password'; }

use constant kTemplate => '/app/tools/bookpub/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 $password1 = $self->getParam('NewPassword');
    my $password2 = $self->getParam('NewPasswordConfirm');

    my $userID = Common::RSApp::GetActiveUserID();
    my $user   = AppUser::DB::Item::User->Lookup( user_id => $userID );

    if ( $self->getParam('formSubmit') ) {

        my $command;
        if ( $password1 && $password2 && $password1 eq $password2 ) {

            # Make sure the password is valid
            my $valid;

            if ( AppUser::DB::Item::User->HasPreviousPassword( $userID, $password1 ) ) {
                my $errMsg = RPS::Message->new( type => "error", code => Common::FormObject::kErrPasswordHistory );
                $command = "/bookpub/user?c=changepw&msg=" . $errMsg->toString;

            } elsif ( $user->email eq $password1 ) {
                my $errMsg = RPS::Message->new( type => "error", code => Common::FormObject::kErrPasswordUnsafe );
                $command = "/bookpub/user?c=changepw&msg=" . $errMsg->toString;

            } else {
                # The UI password validation should catch all format errors.  This is just a fallback.
                if ( AppUser::DB::Item::User->IsValidPassword( $password1 ) ) {
                    $valid = 1;
                } else {
                    my $errMsg = RPS::Message->new( type => "error", code => Common::FormObject::kErrPasswordInvalid );
                    $command = "/bookpub/user?c=changepw&msg=" . $errMsg->toString;
                }
            }

            if ( $valid ) {
                # Before saving the new password, copy the old one to the password history

                my $oldPassword = $user->password;
                my $lastChanged = $user->last_changed;
                $user->ArchivePassword( $userID, $oldPassword, $lastChanged);

                # update the password

                my $now = strftime "%Y-%m-%d %H:%M:%S", localtime time;
                $user->last_changed($now);

                if ( $user->must_change ) {
                    # If must_change is set, once a valid password is entered the user will be
                    # forced to login using their new password before they can access the site.
                    # Also, if must_change is set then the special change password page is the
                    # only allowable page.  Any other app/area commands will be redirected to
                    # the login page.

                    $self->addMessageXML( type => "success", code => Common::FormObject::kSuccessFormSubmit );
                    $response = RSApache::Response::XSLT->new( $self->{xml}, '/app/tools/appuser/templates/password_logout.xsl');

                    # Log the user out
                    my $session = RSApache::RSWebApp::GetSession();
                    if ( $session->IsValid() ) {
                        if ( $session->End() ) {
                            print STDERR "BookPub/User/Command/ChangePW -- user_id $userID session ended\n";
                        } else {
                            print STDERR "BookPub/User/Command/ChangePW -- user_id $userID session end failed: ".$session->errstr."\n";
                        }
                    }

                } else {
                    my $msg = RPS::Message->new( type => "success", code => Common::FormObject::kSuccessFormSubmit );
                    $command = "/bookpub/user?c=profile&msg=" . $msg->toString;
                }

                $user->must_change(0);
                $user->password(AppUser::DB::Item::User->HashPassword($password1));
                $user->save();

            }

            #			$command = AppUser::User::Command::Profile->new(msg => $msg->toString);
        } else {
            my $errMsg = RPS::Message->new( type => "error", code => Common::FormObject::kErrPasswordMismatch );
            $command = "/bookpub/user?c=changepw&msg=" . $errMsg->toString;

            #			$command = AppUser::User::Command::ChangePW->new(msg => $errMsg->toString);
        }
        $response = RSApache::Response::Redirect->new($command) if( !$response );
    } else {
        $response = RSApache::Response::XSLT->new( $self->{xml}, kTemplate );
    }

    return $response;
}

1;

