package UserLib::Login;

#
# if(already logged in)
# 	- send them to a return_to or home page
# else if(submitting login info)
# 	if valid info
# 		- create session
# 		- send to return_to or home page
# else
# 	- display login page
# 	- pre-fill email if we have it
#

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

use lib ('/app/tools/common/lib');
use Common::Consts;
use RSApache::Session;
use RSApache::RSApp;
use base 'RSApache::RSApp';

# Add libs here
use lib '/app/tools/data_classes/lib';
use Item::User::User;

sub new {
    my $class = shift;
    my $self  = $class->SUPER::new(@_);
    return $self;
}

sub execute {
    my $self = shift;

    # is someone already logged in?
    # TODO: how do I know the client home page URL?
    # get cname from Consts.pm
    my $redirect = ( $self->GetParam("redirect") ) ? uri_escape( $self->GetParam("redirect") ) : $Common::Consts::URLS{login_test_home};
    my $sessionObj = new RSApache::Session();

    # are they already logged in?
    if ( $sessionObj->IsValid() ) {

        # redirect them
        $self->Redirect = $redirect;
    }

    # submitting login info
    else {
        if ( $self->GetParam("email") && $self->GetParam("password") ) {
            my $email    = $self->GetParam("email");
            my $password = $self->GetParam("password");

            # did we get something?
            if ( defined $email && $email ne "" ) {
                my $userObj = new Item::User::User( email => $email );

                # is this email from an existing user?
                if ( defined $userObj && $userObj->Email eq $email ) {

                    # did we get the right password?
                    if ( defined $password && $password ne '' && $userObj->IsPassword($password) ) {

                        # successful login!

                        # TODO: We need to look up this user in the client table to find
                        # their client id and make sure it matches the ENV{client_id}

                        # TODO: do we check to see if this was successful?
                        $sessionObj->Create($userObj);
                        $self->Redirect = $redirect;
                    } else {

                        # error: password doesn't match
                        $self->AddFormFieldValue( { name => "email",    value      => $email } );
                        $self->AddFormFieldValue( { name => "password", error_type => "password_mismatch" } );
                    }
                } else {

                    # error: invalid email
                    $self->AddFormFieldValue( { name => "email", value => $email, error_type => "email_not_found" } );
                }
            } else {

                # error: blank email (javascript should catch this)
                $self->AddFormFieldValue( { name => "email", value => $email, error_type => "email_blank" } );
            }
        } else {

            # display the login page:
            #   - get email from inactive cookie
            my $userObj = $sessionObj->ActiveUser;
            if ( defined $userObj && $userObj->Email ne '' ) {
                $self->AddFormFieldValue( { name => "email", value => $userObj->Email } );
            }
        }
        $self->Stylesheet = "main.xsl";
    }

    return 1;
}

# small wrapper around setting up the xml data structure
sub AddFormFieldValue {
    my $self = shift;
    my $args = shift;

    push @{ $self->{xml}->{form}->{fields}->{field} }, $args;

    if ( exists $args->{error_type} ) {
        $self->{xml}->{form}->{errors} = 1;
    }
}

###
1;    # Play nicely.
###
