package PciIds::Html::Users;
use strict;
use warnings;
use PciIds::Html::Util;
use PciIds::Html::Forms;
use PciIds::Email;
use PciIds::Users;
use PciIds::Address;
use CGI;
use CGI::Cookie;
use Apache2::Const qw(:common);
use Apache2::SubRequest;
use APR::Table;

use base 'Exporter';

our @EXPORT = qw(&checkLogin &notLoggedComplaint);

sub genRegisterForm( $$$$ ) {
	my( $req, $args, $error, $values ) = @_;
	genHtmlHead( $req, 'Register a new user', undef );
	print "<div class='top'>\n";
	print '<h1>Register a new user</h1>';
	genLocMenu( $req, $args, [ [ 'Log in', 'login' ], [ 'Help', 'help', 'account' ] ] );
	print "<div class='clear'></div></div>\n";
	print '<div class="error">'.$error.'</div>' if( defined $error );
	print '<form name="register" id="register" method="POST" action="">
		<table>';
	genForm( [ [ 'Email:', 'text', 'email', 'maxlength="255"' ],
		[ '', 'submit', 'register', 'value="Register"' ] ], $values );
	print '</table></form>';
	genHtmlTail();
	return OK;
}

sub registerForm( $$ ) {#Form for registering a new user
	my( $req, $args ) = @_;
	return genRegisterForm( $req, $args, undef, {} );
}

sub loginCheck( $$ ) {
	my( $login, $tables ) = @_;
	return undef if( ( not defined $login ) || ( $login eq '' ) );#empty login is ok
	return 'Login too long' if( ( length $login ) > 50 );
	return 'Login contains invalid characters' unless( $login =~ /^[-_a-zA-Z0-9]+$/ );
	return 'This login already exists' if( $tables->hasLogin( $login ) );
	return undef;
}

sub registerSubmit( $$$ ) {#A registration form has been submited
	my( $req, $args, $tables ) = @_;
	my( $data, $error ) = getForm( {
		'email' => sub {
			return emailCheck( shift, $tables );
		}
	}, [] );
	return genRegisterForm( $req, $args, $error, $data ) if( defined $error );
	my $site = $req->hostname();
	my $url = 'https://'.$req->hostname().setAddrPrefix( $req->uri(), 'mods' );
	sendMail( $data->{'email'}, 'Confirm registration', "Someone, probably you, requested registration of this address\n".
		"for the $site site. If it wasn't you, please ignore this email message.\n".
		"\nOtherwise, please continue by filling in the form at this address:".
		"\n".$url.'?action=register-confirm?email='.$data->{'email'}.'?confirm='.emailConfirm( $data->{'email'} )."\n".
		"\nThank you\n".
		"\n(This is an autogenerated email, do not respond to it)" );
	genHtmlHead( $req, 'Registration email sent', undef );
	print "<div class='top'>\n";
	print "<h1>Registration email sent</h1>\n";
	genLocMenu( $req, $args, [ [ 'Log in', 'login' ], [ 'Help', 'help', 'account' ] ] );
	print "<div class='clear'></div></div>\n";
	print '<p>
			An email containing further information has been sent to you.
			Please follow these instruction to finish the registration process.';
	genHtmlTail();
	return OK;
}

sub genConfirmForm( $$$$ ) {
	my( $req, $args, $error, $values ) = @_;
	genHtmlHead( $req, 'Confirm registration', undef );
	print "<div class='top'>\n";
	print '<h1>Confirm registration</h1>';
	genLocMenu( $req, $args, [ [ 'Register', 'register' ], [ 'Help', 'help', 'account' ] ] );
	print "<div class='clear'></div></div>\n";
	print '<div class="error">'.$error.'</div>' if( defined $error );
	print '<p>Email address: '.encode( $values->{'email'} );
	print '<form name="register-confirm" id="register-confirm" method="POST" action="">';
	print '<div class="hidden"><p><input type="hidden" value="'.encode( $values->{'email'} ).'" name="email"><input type="hidden" value="'.encode( $values->{'confirm'} ).'" name="confirm"></div>';
	print '<table>';
	genForm( [ [ 'Login (Optional):', 'text', 'login', 'maxlength="50"' ],
		[ 'Password:', 'password', 'password' ],
		[ 'Confirm password:', 'password', 'confirm_password' ],
		[ '', 'submit', 'register', 'value=Register' ] ], $values );
	print '</table></form>';
	genHtmlTail();
	return OK;
}

sub usedAddress( $$ ) {
	my( $req, $args ) = @_;
	genHtmlHead( $req, 'Used address', undef );
	print "<div class='top'>\n";
	print "<h1>Used address</h1>\n";
	genLocMenu( $req, $args, [ [ 'Log in', 'login' ], [ 'Reset password', 'respass' ], [ 'Register', 'register' ], [ 'Help', 'help', 'account' ] ] );
	print "<div class='clear'></div></div>\n";
	print '<div class="error">
		<p>
			An account for this address is already registered.
			Please, reset or remember your password or start again with a different address.
		</div>';
	genHtmlTail();
	return 0;
}

sub checkRegHash( $$$$$ ) {
	my( $req, $args, $tables, $email, $hash ) = @_;
	if( ! checkConfirmHash( $email, $hash ) ) {
		genHtmlHead( $req, 'Invalid registration request', undef );
		print '<h1>Invalid registration request</h1>
			<div class="error">
			<p>
				This registration request is invalid.
				Are you sure you got it from the registration email?
			</div>';
		genHtmlTail();
		return 0;
	} elsif( $tables->hasEmail( $email ) ) {
		return usedAddress( $req, $args );
	} else {
		return 1;
	}
}

sub confirmForm( $$$$ ) {
	my( $req, $args, $tables, $auth ) = @_;
	return HTTPRedirect( $req, 'https://'.$req->hostname().$req->uri().buildArgs( $args ) ) unless $auth->{'ssl'};
	if( ! checkRegHash( $req, $args, $tables, $args->{'email'}, $args->{'confirm'} ) ) {
		return OK;
	} else {
		return genConfirmForm( $req, $args, undef, $args );
	}
}

sub passLenCheck( $ ) {
	my( $pass ) = @_;
	return ( ( length $pass ) >= 4 ) ? undef : 'Password must have at least 4 characters';
}

sub passSameCheck( $ ) {
	my( $data ) = @_;
	return ( ( ( defined $data->{'password'} ) != ( defined $data->{'confirm_password'} ) ) || ( ( defined $data->{'password'} ) && ( $data->{'password'} ne $data->{'confirm_password'} ) ) ) ? 'Passwords do not match' : undef;
}

sub confirmSubmit( $$$ ) {
	my( $req, $args, $tables ) = @_;
	my( $data, $error ) = getForm( {
		'email' => sub {
			return emailCheck( shift, $tables );
		},
		'confirm' => undef,
		'login' => sub {
			return loginCheck( shift, $tables );
		},
		'password' => \&passLenCheck,
		'confirm_password' => undef }, [ \&passSameCheck ] );
	return OK if( ! checkRegHash( $req, $args, $tables, $data->{'email'}, $data->{'confirm'} ) );#Not much info, but this is an attack anyway
	return genConfirmForm( $req, $args, $error, $data ) if( defined $error );
	unless( addUser( $tables, $data->{'login'}, $data->{'email'}, $data->{'password'} ) ) {
		usedAddress( $req, $args );
		return OK;
	}
	genHtmlHead( $req, 'Registered', undef );
	print "<div class='top'>\n";
	print "<h1>Registered</h1>\n";
	genLocMenu( $req, $args, [ [ 'Log in', 'login' ], [ 'Help', 'help', 'account' ] ] );
	print "<div class='clear'></div></div>\n";
	print '<p>
			You have registered successfully.';
	genHtmlTail();
	return OK;
}

sub genLoginForm( $$$$ ) {
	my( $req, $args, $error, $values ) = @_;
	$req->headers_out->add( 'Set-Cookie' => new CGI::Cookie( -name => 'cookie-test', -value => 1 ) );
	genHtmlHead( $req, 'Login', undef );
	print "<div class='top'>\n";
	print '<h1>Login</h1>';
	genLocMenu( $req, $args, [ [ 'Register', 'register' ], [ 'Reset password', 'respass' ], [ 'Help', 'help', 'account' ] ] );
	print "<div class='clear'></div></div>\n";
	print '<div class="error"><p>'.$error.'</div>' if( defined $error );
	print '<form name="login" id="login" method="POST" action="'.setAddrPrefix( $req->uri(), 'mods' ).buildExcept( 'action', $args ).'?action=login"><table>';
	genForm( [ [ 'Login name or email:', 'text', 'login', 'maxlength="255"' ],
		[ 'Password:', 'password', 'password' ],
		[ '', 'submit', 'login', 'value="Login"' ] ], $values );
	print '</table></form>';
	genHtmlTail();
	return OK;
}

sub loginForm( $$$ ) {
	my( $req, $args, $tables, $auth ) = @_;
	return HTTPRedirect( $req, 'https://'.$req->hostname().$req->uri().buildArgs( $args ) ) unless( $auth->{'ssl'} );
	return genLoginForm( $req, $args, undef, {} );
}

sub loginSubmit( $$$ ) {
	my( $req, $args, $tables ) = @_;
	my( $data, $error ) = getForm( {
		'login' => undef,
		'password' => undef
	}, [] );
	my $logged = 0;
	my $cookies = fetch CGI::Cookie;
	unless( $cookies->{'cookie-test'} ) {
		return genLoginForm( $req, $args, 'You need to enable cookies', $data );
	}
	my( $id, $passwd, $email, $last ) = $tables->getLogInfo( $data->{'login'} );
	if( defined $passwd && defined $data->{'password'} ) {
		my $salted = saltedPasswd( $email, $data->{'password'} );
		$logged = $salted eq $passwd;
	}
	if( $logged ) {
		$req->headers_out->add( 'Set-Cookie' => new CGI::Cookie( -name => 'auth', -value => genAuthToken( $tables, $id, $req, undef, $email ) ) );
		$args->{'action'} = ( defined $args->{'redirectaction'} ) ? $args->{'redirectaction'} : 'list';
		my $prefix = ( !defined( $args->{'action'} ) or ( $args->{'action'} eq '' ) or ( $args->{'action'} eq 'list' ) ) ? 'read' : 'mods';
		my $url = "http://".$req->hostname().setAddrPrefix( $req->uri(), $prefix ).buildExcept( 'redirectaction', $args );
		genHtmlHead( $req, 'Logged in', undef );
		print "<div class='top'>\n";
		print '<h1>Logged in</h1>';
		genPath( $req, PciIds::Address::new( $req->uri() ), 1 );
		print "<div class='clear'></div></div>\n";
		print "<p>You are logged in" . ( defined $args->{'redirectaction'} ? ", continue with your <a href='$url'>action</a>.\n" : ".\n" );
		print '<div class="lastlog"><p>'.encode( $last ).'</div>' if( defined( $last ) );
		genHtmlTail();
		return OK;
	} else {
		return genLoginForm( $req, $args, 'Invalid login credetials', $data );
	}
}

sub logout( $$ ) {
	my( $req, $args, $tables, $auth ) = @_;
	$req->headers_out->add( 'Set-Cookie' => new CGI::Cookie( -name => 'auth', -value => '0' ) );
	return PciIds::Html::List::list( $req, $args, $tables, {} );
}

sub checkLogin( $$ ) {
	my( $req, $tables ) = @_;
	my $cookies = fetch CGI::Cookie;
	my( $authed, $id, $regen, $rights, $error, $name ) = checkAuthToken( $tables, $req, defined( $cookies->{'auth'} ) ? $cookies->{'auth'}->value : undef );
	if( $regen ) {
		$req->headers_out->add( 'Set-Cookie' => new CGI::Cookie( -name => 'auth', -value => genAuthToken( $tables, $id, $req, $rights, $name ) ) );
	}
	my $hterror = $authed ? '' : '<div class="error"><p>'.$error.'</div>';
	return { 'authid' => $authed ? $id : undef, 'accrights' => $rights, 'logerror' => $hterror, 'name' => $authed ? $name : undef };
}

sub notLoggedComplaint( $$$ ) {
	my( $req, $args, $auth ) = @_;
	return HTTPRedirect( $req, 'https://'.$req->hostname().$req->uri().buildArgs( $args ) ) unless $auth->{'ssl'};
	$args->{'redirectaction'} = $args->{'action'};
	return genLoginForm( $req, $args, 'This action requires you to be logged in', undef );
}

sub genResetPasswdForm( $$$$ ) {
	my( $req, $args, $error, $values ) = @_;
	genHtmlHead( $req, 'Reset password', undef );
	print "<div class='top'>\n";
	print "<h1>Reset password</h1>\n";
	genLocMenu( $req, $args, [ [ 'Log in', 'login' ], [ 'Register', 'register' ], [ 'Help', 'help', 'account' ] ] );
	print "<div class='clear'></div></div>\n";
	print "<p>If you forgot your password (or didn't create one yet), you can reset it to a new value here.\n";
	print "Provide your email address here and further instructions will be sent to you.\n";
	print '<div class="error">'.$error.'</div>' if( defined $error );
	print '<form name="respass" id="respass" method="POST" action="">
		<table>';
	genForm( [ [ 'Email:', 'text', 'email', 'maxlength="255"' ],
		[ '', 'submit', 'respass', 'value="Send"' ] ], $values );
	print '</table></form>';
	genHtmlTail();
	return OK;
}

sub resetPasswdForm( $$$$ ) {
	my( $req, $args ) = @_;
	return genResetPasswdForm( $req, $args, undef, {} );
}

sub resetPasswdFormSubmit( $$$ ) {
	my( $req, $args, $tables ) = @_;
	my( $data, $error ) = getForm( {
		'email' => undef
	}, [] );
	my( $id, $login, $passwd ) = $tables->resetInfo( $data->{'email'} );
	if( defined( $id ) ) {
		$login = '' unless( defined( $login ) );
		my $site = $req->hostname();
		my $url = 'https://'.$req->hostname().setAddrPrefix( $req->uri(), 'mods' );
		my $hash = genResetHash( $id, $data->{'email'}, $login, $passwd );
		sendMail( $data->{'email'}, 'Reset password',
			"A request to reset password for the $site site was received for this address\n".
			"If you really wish to get a new password, visit this link:\n\n".
			$url.'?action=respass-confirm?email='.$data->{'email'}.'?confirm='.$hash."\n".
			"\n\nThank you\n".
			"\n(This is an autogenerated email, do not respond to it)" );
		genHtmlHead( $req, 'Reset password', undef );
		print "<div class='top'>\n";
		print "<h1>Reset password</h1>\n";
		genLocMenu( $req, $args, [ [ 'Log in', 'login' ], [ 'Help', 'help', 'account' ] ] );
		print "<div class='clear'></div></div>\n";
		print "<p>An email with information has been sent to your address.\n";
		genHtmlTail();
		return OK;
	} else {
		$error = '<p>This email address is not registered. Check it for typos or register it.';
	}
	return genResetPasswdForm( $req, $args, $error, $data ) if( defined( $error ) );
}

sub genResetPasswdConfigForm( $$$$$$ ) {
	my( $req, $args, $error, $values, $email, $hash ) = @_;
	genHtmlHead( $req, 'Reset password', undef );
	print "<div class='top'>\n";
	print "<h1>Reset password</h1>\n";
	genLocMenu( $req, $args, [ [ 'Log in', 'login' ], [ 'Help', 'help', 'account' ] ] );
	print "<div class='clear'></div></div>\n";
	print '<div class="error">'.$error.'</div>' if( defined $error );
	print "<p>You can enter new password here:\n";
	print '<form name="respass-confirm" id="respass-confirm" method="POST" action="">
		<table>';
	genForm( [ [ 'Password:', 'password', 'password' ],
		[ 'Confirm password:', 'password', 'confirm_password' ],
		[ '', 'submit', 'respass', 'value="Send"' ] ], $values );
	print "</table>";
	print "<input type='hidden' name='email' value='".encode( $email )."'><input type='hidden' name='hash' value='".encode( $hash )."'>\n";
	print "</form>\n";
	genHtmlTail();
	return OK;
}

sub resetPasswdConfirmForm( $$$$ ) {
	my( $req, $args, $tables, $auth ) = @_;
	my( $email, $hash ) = ( $args->{'email'}, $args->{'confirm'} );
	my( $id, $login, $passwd ) = $tables->resetInfo( $email );
	my $myHash;
	return HTTPRedirect( $req, 'https://'.$req->hostname().$req->uri().buildArgs( $args ) ) unless $auth->{'ssl'};
	$myHash = genResetHash( $id, $email, $login, $passwd ) if( defined( $id ) );
	if( defined( $myHash ) && ( $myHash eq $hash ) ) {#Ok, it is his mail and he asked
		return genResetPasswdConfigForm( $req, $args, undef, {}, $email, $hash );
	} else {
		genHtmlHead( $req, 'Reset password', undef );
		print "<h1>Reset password</h1>\n";
		print "<p>Provided link is not valid. Did you use it already?\n";
		print "<p>You can get a <a href='".$req->uri()."?action=respass'>new one</a>.\n";
		genHtmlTail();
		return OK;
	}
}

sub resetPasswdConfirmFormSubmit( $$$ ) {
	my( $req, $args, $tables ) = @_;
	my( $data, $error ) = getForm( {
		'password' => \&passLenCheck,
		'confirm_password' => undef,
		'email' => undef,
		'hash' => undef
	}, [ \&passSameCheck ] );
	my( $email, $hash ) = ( $data->{'email'}, $args->{'confirm'} );
	if( defined( $error ) ) {
		return genResetPasswdConfigForm( $req, $args, $error, $data, $email, $hash );
	} else {
		my( $id, $login, $passwd ) = $tables->resetInfo( $email );
		my $myHash;
		$myHash = genResetHash( $id, $email, $login, $passwd ) if( defined( $id ) );
		if( defined( $myHash ) && ( $myHash eq $hash ) ) {
			changePasswd( $tables, $id, $data->{'password'}, $email );
			genHtmlHead( $req, 'Reset password', undef );
			print "<div class='top'>\n";
			print "<h1>Reset password</h1>\n";
			genLocMenu( $req, $args, [ [ 'Log in', 'login' ], [ 'Help', 'help', 'account' ] ] );
			print "<div class='clear'></div></div>\n";
			print "<p>Your password was successfuly changed.\n";
			genHtmlTail();
			return OK;
		} else {
			return genResetPasswdConfigForm( $req, $args, $error, $data, $email, $hash );
		}
	}
}

sub genProfileForm( $$$$$$ ) {
	my( $req, $args, $auth, $error, $data, $info ) = @_;
	genHtmlHead( $req, 'User profile', undef );
	delete $data->{'current_password'};
	delete $data->{'confirm_password'};
	delete $data->{'password'};
	print "<div class='top'>\n";
	print "<h1>User profile</h1>\n";
	genLocMenu( $req, $args, [ logItem( $auth ), [ 'Notifications', 'notifications' ], [ 'Help', 'help', 'profile' ] ] );
	print "<div class='clear'></div></div>\n";
	print '<div class="error"><p>'.$error.'</div>' if defined $error;
	print "<div class='info'><p>$info</div>\n" if defined $info;
	print '<form name="profile" id="profile" method="POST" action=""><table>';
	genForm( [ [ 'Email:', 'text', 'email', 'maxlength="255"' ],
		[ 'Login:', 'text', 'login', 'maxlength="50"' ],
		[ 'Xmpp:', 'text', 'xmpp', 'maxlength="255"' ],
		[ 'New password:', 'password', 'password' ],
		[ 'Confirm password:', 'password', 'confirm_password' ],
		[ 'Current password:', 'password', 'current_password' ],
		[ 'Email batch time (min):', 'text', 'email_time', 'maxlength="10"' ],
		[ 'Xmpp batch time (min):', 'text', 'xmpp_time', 'maxlength="10"' ],
		[ '', 'submit', 'profile', 'value="Submit"' ] ], $data );
	print '</table></form>';
	genHtmlTail();
	return OK;
}

sub profileForm( $$$$ ) {
	my( $req, $args, $tables, $auth ) = @_;
	return notLoggedComplaint( $req, $args, $auth ) unless defined $auth->{'authid'};
	return HTTPRedirect( $req, 'https://'.$req->hostname().$req->uri().buildArgs( $args ) ) unless $auth->{'ssl'};
	return genProfileForm( $req, $args, $auth, undef, $tables->profileData( $auth->{'authid'} ), undef );
}

sub checkNum( $$ ) {
	my( $value, $name ) = @_;
	return ( "$name has invalid number format", '0' ) unless ( $value =~ /\d+/ );
	return undef;
}

sub profileFormSubmit( $$$$ ) {
	my( $req, $args, $tables, $auth ) = @_;
	return notLoggedComplaint( $req, $args, $auth ) unless defined $auth->{'authid'};
	my $oldData = $tables->profileData( $auth->{'authid'} );
	my( $data, $error ) = getForm( {
		'email' => sub {
			my $email = shift;
			return undef if ( defined $email ) && ( $email eq $oldData->{'email'} );
			return emailCheck( $email, $tables );
		},
		'login' => sub {
			my $login = shift;
			$login = undef if ( defined $login ) && ( $login eq '' );
			return undef if ( defined $login ) && ( defined $oldData->{'login'} ) && ( $oldData->{'login'} eq $login );
			return ( undef, $login ) if ( !defined $login ) && ( !defined $oldData->{'login'} );
			return loginCheck( $login, $tables );
		},
		'xmpp' => sub {
			my $xmpp = shift;
			return ( undef, undef ) if ( !defined $xmpp ) || ( $xmpp eq '' );
			return "Xmpp address limit is 255" if length $xmpp > 255;
			return "Invalid Xmpp address" unless $xmpp =~ /^([^'"\@<>\/]+\@)?[^\@'"<>\/]+(\/.*)?/;
			return undef;
		},
		'password' => sub {
			my $passwd = shift;
			$passwd = undef if ( defined $passwd ) && ( $passwd eq '' );
			return ( undef, undef ) unless defined $passwd;
			return passLenCheck( $passwd );
		},
		'confirm_password' => undef,
		'current_password' => undef,
		'email_time' => sub {
			return checkNum( shift, "Email batch time" );
		},
		'xmpp_time' => sub {
			return checkNum( shift, "Xmpp batch time" );
		}
	}, [ sub {
		my $data = shift;
		return undef unless defined $data->{'password'};
		return passSameCheck( $data );
	}, sub {
		my $data = shift;
		my $change = 0;
		$change = 1 if $data->{'email'} ne $oldData->{'email'};
		$change = 1 if ( ( ( defined $data->{'login'} ) != ( defined $oldData->{'login'} ) ) || ( ( defined $data->{'login'} ) && ( defined $oldData->{'login'} ) && ( $data->{'login'} ne $oldData->{'login'} ) ) );
		$change = 1 if ( defined $data->{'password'} ) && ( $data->{'password'} ne '' );
		return undef unless $change;
		my $logged = 0;
		my( $id, $passwd, $email, $last ) = $tables->getLogInfo( $oldData->{'email'} );
		if( defined $passwd && defined $data->{'current_password'} ) {
			my $salted = saltedPasswd( $email, $data->{'current_password'} );
			$logged = ( $salted eq $passwd ) && ( $id == $auth->{'authid'} );
		}
		return "You need to provide correct current password to change email, login or password" unless $logged;
		return undef;
	} ] );
	return genProfileForm( $req, $args, $auth, $error, $data, undef ) if defined $error;
	pushProfile( $tables, $auth->{'authid'}, $oldData, $data );
	return genProfileForm( $req, $args, $auth, undef, $data, "Profile updated." );
}

1;
