// 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) 2002 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
// 
// Contributor(s): 

importPackage(java.lang);
importClass(Packages.com.silverwrist.dynamo.Namespaces);
importClass(Packages.com.silverwrist.dynamo.UserInfoNamespace);
importPackage(Packages.com.silverwrist.dynamo.dialog);
importPackage(Packages.com.silverwrist.dynamo.iface);
importPackage(Packages.com.silverwrist.dynamo.mail);
importPackage(Packages.com.silverwrist.dynamo.util);
importClass(Packages.com.silverwrist.venice.VeniceNamespaces);
importPackage(Packages.com.silverwrist.venice.frame);
importPackage(Packages.com.silverwrist.venice.session);

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 already logged in, must log out first
  dynamo.scriptReturn(new ErrorBox(null,"You cannot create a new account while logged in on an existing one. "
                                      + "You must log out first.",target));

// Load the new account dialog.
loader = cast.queryDialogLoader(req);
dlg = loader.loadDialogResource("new_account.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 login - bounce back to the target
  dynamo.scriptReturn(new Redirect("SERVLET",target));
  
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("Dialog validation failed",e);
  dlg.setErrorMessage(dynamo.exceptionMessage(e) + "  Please try again.");
  vlib.setLocation(req,target);
  vlib.setDisplayLogin(req,false);
  dynamo.scriptReturn(new FrameDialog(dlg));

} // end catch

if (op=="create")
{ // check the two passwords
  pass1 = dlg.getValue("pass1");
  pass2 = dlg.getValue("pass2");
  if (!(pass1.equals(pass2)))
  { // the two passwords don't match - 
    dlg.setErrorMessage("The passwords do not match.  Please try again.");
    vlib.setLocation(req,target);
    vlib.setDisplayLogin(req,false);
    dynamo.scriptReturn(new FrameDialog(dlg));

  } // end if

  // get the profile information to a local object store
  temp_profile = new MemoryObjectStore("login profile");
  PropertyUtils.setIfNonNull(temp_profile,VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.prefix",
                             dlg.getValue("prefix"));
  temp_profile.setObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.given",dlg.getValue("first"));
  s = dlg.getValue("mid");
  if (s!=null)
    temp_profile.setObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.mi",
                           new Character(s.toString().charAt(0)));
  temp_profile.setObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.family",dlg.getValue("last"));
  PropertyUtils.setIfNonNull(temp_profile,VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.suffix",
                             dlg.getValue("suffix"));
  temp_profile.setObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"locality",dlg.getValue("loc"));
  temp_profile.setObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"region",dlg.getValue("reg"));
  temp_profile.setObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"postal.code",dlg.getValue("pcode"));
  temp_profile.setObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"country",dlg.getValue("country"));
  PropertyUtils.setIfNonNull(temp_profile,VeniceNamespaces.USER_SETTINGS_NAMESPACE,"password.reminder",
                             dlg.getValue("remind"));

  // Create the DynamoUser object.
  umgmt = cast.queryUserManagement(req_help.getRequestObject(Namespaces.DYNAMO_OBJECT_NAMESPACE,"users"));
  new_user = umgmt.createUser(dlg.getValue("user"),dlg.getValue("email"));

  // Set the initial authentication info.
  new_user.setAuthenticationData(new_user,UserInfoNamespace.NAMESPACE,UserInfoNamespace.AUTH_DEFAULT,"",pass1);

  // Copy all default properties to this user.
  udpns = vcast.queryUserDefaultPropertyNamespace(req);
  umgmt.loadUserDefaults(new_user,udpns.getDefaultPropertyNamespaces());

  // Set the "profile last updated" date for the user.
  temp_profile.setObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"last.update",new_user.getCreationDate());

  // Copy in the user properties.
  if (!(PropertyUtils.copyPropertyNamespace(new_user,temp_profile,new_user,
                                            VeniceNamespaces.USER_PROFILE_NAMESPACE)))
    dynamo.scriptReturn(new ErrorBox("Internal Error","Unable to copy profile to new user.",target));
  if (!(PropertyUtils.copyPropertyNamespace(new_user,temp_profile,new_user,
                                            VeniceNamespaces.USER_SETTINGS_NAMESPACE)))
    dynamo.scriptReturn(new ErrorBox("Internal Error","Unable to copy settings to new user.",target));

  // Add this user to the "all users" group.
  srm = cast.querySecurityReferenceMonitor(req_help.getRequestObject(Namespaces.DYNAMO_OBJECT_NAMESPACE,
                                                                     "srm"));
  srm.getAllUsersGroup().addMember(new_user);

  // Write an audit message indicating the new user was created.
  audit.write(req,new_user,VeniceNamespaces.USER_EVENT_NAMESPACE,"user.created");

  // Generate an E-mail confirmation number and add it to the user properties.
  confnum = vlib.randomConfirmationNumber();
  new_user.setObject(new_user,VeniceNamespaces.USER_SETTINGS_NAMESPACE,"confirmation.number",
                     cast.toIntegerObject(confnum));

  // At this point, the user is completely set up, so act like we're logging in as that user.
  req_help.getSession().setObject(SessionInfoParams.NAMESPACE,SessionInfoParams.ATTR_USER,new_user);
  new_user.setLastAccessDate(new_user,new java.util.Date());
  dynamo.exec("/util/setup_user.js");

  // Generate and send an E-mail message to the user with the confirmation number.
  mailprov = cast.queryMailMessageProvider(req);
  msg = mailprov.createSystemMessage(req);
  msg.addRecipient(MailMessage.RECIP_TO,new_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",new_user.getName());
  msg.setVariable("confnum",cast.toIntegerObject(confnum));
  msg.send();

  // Write an audit message.
  audit.write(req,new_user,VeniceNamespaces.USER_EVENT_NAMESPACE,"send.confirm.email",
              new_user.getEMailAddress());

  // Now bounce us to the "verification" dialog.
  dynamo.scriptOutput(new Redirect("SERVLET","verify_email.js.vs?tgt=" + stringutils.encodeURL(target)));

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

} // end else
