// The contents of this file are subject to the Mozilla Public License Version 1.1
// (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
// WARRANTY OF ANY KIND, either express or implied. See the License for the specific
// language governing rights and limitations under the License.
// 
// The Original Code is the Venice Web Communities System.
// 
// The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
// for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
// Copyright (C) 2003 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
// 
// Contributor(s): 

importClass(Packages.com.silverwrist.dynamo.Namespaces);
importPackage(Packages.com.silverwrist.dynamo.iface);
importPackage(Packages.com.silverwrist.dynamo.mail);
importPackage(Packages.com.silverwrist.dynamo.security);
importPackage(Packages.com.silverwrist.dynamo.util);
importClass(Packages.com.silverwrist.venice.VeniceNamespaces);

req = bsf.lookupBean("request");
req_help = bsf.lookupBean("request_help");
target = req_help.getParameterString("tgt");
if (target==null)
  target = "top.js.vs";
vlib.setOnError(req,target);

// Check the user account.
user = vlib.getUser(req);
if (user.isAnonymous())
{ // user not logged in, must log in first - so bounce us to the login dialog
  new_target = "verify_email.js.vs?tgt=" + stringutils.encodeURL(target);
  dynamo.scriptReturn(new Redirect("SERVLET","login.js.vs?tgt=" + stringutils.encodeURL(new_target)));

} // end if

// If user is already verified, this is a no-op.
if (!PropertyUtils.hasProperty(user,VeniceNamespaces.USER_SETTINGS_NAMESPACE,"confirmation.number"))
  dynamo.scriptReturn(new Redirect("SERVLET",target));
confnum = cast.toInteger(user.getObject(VeniceNamespaces.USER_SETTINGS_NAMESPACE,"confirmation.number"));

// Load the verification dialog.
loader = cast.queryDialogLoader(req);
dlg = loader.loadDialogResource("verify.dlg.xml");

if (req_help.isVerb("GET"))
{ // fill in the dialog for a GET and return it
  dlg.setValue("tgt",target);
  vlib.setLocation(req,target);
  vlib.setDisplayLogin(req,false);
  dynamo.scriptReturn(new FrameDialog(dlg));

} // end if

// Everything that follows is for a POST operation
op = dlg.getClickedButton(req) + "";
if (op=="cancel")  // user cancelled verification - bounce us back to the target
  dynamo.scriptReturn(new Redirect("SERVLET",target));
else if (op=="send.again")
{ // generate a new confirmation number before we re-send the message
  confnum = vlib.randomConfirmationNumber();
  user.setObject(user,VeniceNamespaces.USER_SETTINGS_NAMESPACE,"confirmation.number",
                 cast.toIntegerObject(confnum));

  // send the verification E-mail message again
  mailprov = cast.queryMailMessageProvider(req);
  msg = mailprov.createSystemMessage(req);
  msg.addRecipient(MailMessage.RECIP_TO,user.getEMailAddress());
  globals = vcast.getGlobalPropertiesStore(req);
  msg.setSubject(globals.getObject(VeniceNamespaces.MAIL_MESSAGES_NAMESPACE,
                                   "confirm.message.title").toString());
  blocks = vcast.getGlobalBlocksStore(req);
  msg.setText(blocks.getObject(VeniceNamespaces.MAIL_MESSAGES_NAMESPACE,"confirm.message").toString());
  msg.setVariable("username",user.getName());
  msg.setVariable("confnum",cast.toIntegerObject(confnum));
  msg.send();

  // Record an audit message.
  audit.write(req,user,VeniceNamespaces.USER_EVENT_NAMESPACE,"resend.confirm.email",
              user.getEMailAddress());

  // bounce us back to the dialog
  dlg.setErrorMessage("New confirmation message sent.");
  dlg.setValue("tgt",target);
  vlib.setLocation(req,target);
  vlib.setDisplayLogin(req,false);
  dynamo.scriptReturn(new FrameDialog(dlg));

} // end else if

dlg.load(req);  // load dialog contents
try
{ // validate the dialog contents
  dlg.validate(req);

} // end try
catch (e)
{ // the validation failed - throw an error message
  logger.error("Verify E-Mail dialog failed validation",e);
  dlg.setErrorMessage(dynamo.exceptionMessage(e) + "  Please try again.");
  dlg.setValue("num",null);
  vlib.setLocation(req,target);
  vlib.setDisplayLogin(req,false);
  dynamo.scriptReturn(new FrameDialog(dlg));

} // end catch

if (op=="ok")
{ // the button has been pressed - is the confirmation number correct?
  if (!(dlg.containsValue("num")))
  { // no confirmation number entered!!!
    dlg.setErrorMessage("No confirmation number entered.  Please try again.");
    vlib.setLocation(req,target);
    vlib.setDisplayLogin(req,false);
    dynamo.scriptReturn(new FrameDialog(dlg));

  } // end if

  new_num = cast.toInteger(dlg.getValue("num"));
  if (new_num!=confnum)
  { // confirmation numbers don't match - bogus!
    audit.write(req,user,VeniceNamespaces.USER_EVENT_NAMESPACE,"verify.fail");
    dlg.setErrorMessage("Sorry, the confirmation number doesn't match.  Please try again.");
    dlg.setValue("num",null);
    vlib.setLocation(req,target);
    vlib.setDisplayLogin(req,false);
    dynamo.scriptReturn(new FrameDialog(dlg));

  } // end if

  // we're verified - remove our confirmation number attribute
  audit.write(req,user,VeniceNamespaces.USER_EVENT_NAMESPACE,"verify.ok");
  user.removeObject(user,VeniceNamespaces.USER_SETTINGS_NAMESPACE,"confirmation.number");

  // add us to the "verified users" group
  srm = cast.querySecurityReferenceMonitor(req_help.getRequestObject(Namespaces.DYNAMO_OBJECT_NAMESPACE,
                                                                     "srm"));
  srm.getVerifiedUsersGroup().addMember(user);

  // and that does it - bounce us on to whereever we were going
  dynamo.scriptOutput(new Redirect("SERVLET",target));

} // end if
else
{ // unknown command button pressed!
  logger.error("no known button click on POST to verify_email.js");
  dynamo.scriptOutput(new ErrorBox("Internal Error","Unknown command button pressed","SERVLET",target));

} // end else
