// 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): 

importPackage(java.lang);
importPackage(Packages.com.silverwrist.util);
importClass(Packages.com.silverwrist.dynamo.Namespaces);
importClass(Packages.com.silverwrist.dynamo.UserInfoNamespace);
importPackage(Packages.com.silverwrist.dynamo.dialog);
importPackage(Packages.com.silverwrist.dynamo.except);
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);
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 not logged in, must log in first - so bounce us to the login dialog
  new_target = "profile.js.vs?tgt=" + stringutils.encodeURL(target);
  dynamo.scriptReturn(new Redirect("SERVLET","login.js.vs?tgt=" + stringutils.encodeURL(new_target)));

} // end if

// Create the profile dialog.
loader = cast.queryDialogLoader(req);
dlg = loader.loadDialogResource("user_profile.dlg.xml");

if (req_help.isVerb("GET"))
{ // Get the privacy settings and admin flags.
  priv = cast.toOptionSet(user.getObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"privacy"));
  admin_flags = cast.toOptionSet(user.getObject(VeniceNamespaces.USER_SETTINGS_NAMESPACE,"admin.flags"));

  // Fill in dialog and return it for a GET.
  dlg.setValue("tgt",target);
  // N.B.: do not set pass1, pass2, or remind  
  dlg.setValue("prefix",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                       "name.prefix"));
  dlg.setValue("first",user.getObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.given"));
  dlg.setValue("mid",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                    "name.mi"));
  dlg.setValue("last",user.getObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.family"));
  dlg.setValue("suffix",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                       "name.suffix"));
  dlg.setValue("company",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                        "company.name"));
  dlg.setValue("addr1",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                      "address.1"));
  dlg.setValue("addr2",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                      "address.2"));
  dlg.setValue("pvt_addr",cast.booleanObject(priv.get(0)));
  dlg.setValue("loc",user.getObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"locality"));
  dlg.setValue("reg",user.getObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"region"));
  dlg.setValue("pcode",user.getObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"postal.code"));
  dlg.setValue("country",user.getObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"country"));
  dlg.setValue("phone",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                      "phone.voice"));
  dlg.setValue("pvt_phone",cast.booleanObject(priv.get(1)));
  dlg.setValue("mobile",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                       "phone.mobile"));
  dlg.setValue("pvt_mobile",cast.booleanObject(priv.get(2)));
  dlg.setValue("fax",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                    "phone.fax"));
  dlg.setValue("pvt_fax",cast.booleanObject(priv.get(3)));
  dlg.setValue("email",user.getEMailAddress());
  dlg.setValue("pvt_email",cast.booleanObject(priv.get(4)));
  dlg.setValue("url",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                    "url.homepage"));
  dlg.setValue("descr",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                      "description"));
  dlg.setValue("photo",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                      "url.photo"));
  if (dlg.getValue("photo")==null)
  { // fill in the "no photo" URL
    globals = vcast.getGlobalPropertiesStore(req);
    url = globals.getObject(VeniceNamespaces.CONTENT_LAF_NAMESPACE,"user.nophoto.url");
    urltype = globals.getObject(VeniceNamespaces.CONTENT_LAF_NAMESPACE,"user.nophoto.url.type");
    rewriter = cast.queryURLRewriter(req);
    dlg.setValue("photo",rewriter.rewriteURL(urltype,url));

  } // end if

  if (admin_flags.get(0))
    dlg.setEnabled("photo",false);

  dlg.setValue("no_mass_mail",cast.booleanObject(user.isNoSpam()));
  dlg.setValue("locale",user.getObject(VeniceNamespaces.USER_SETTINGS_NAMESPACE,"locale"));
  dlg.setValue("tz",user.getObject(VeniceNamespaces.USER_SETTINGS_NAMESPACE,"timezone"));

  // prepare the dialog and return it
  dlg.setRenderParam("rtgt",stringutils.encodeURL(target));
  vlib.setLocation(req,target);
  vlib.setDisplayLogin(req,false);
  dynamo.scriptReturn(new FrameDialog(dlg));

} // end if

// everything that follows here 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);

  // if a new password has been specified, make sure it was properly specified twice
  pass1 = dlg.getValue("pass1");
  pass2 = dlg.getValue("pass2");
  if (stringutils.isNotEmpty(pass1))
  { // dest password equality
    if (stringutils.isEmpty(pass2) || !(pass1.equals(pass2)))
      throw new DynamoException("The specified passwords do not match.");

  } // end if
  else if (stringutils.isNotEmpty(pass2))
    throw new DynamoException("The specified passwords do not match.");

} // 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.");

  // have to re-prep the user photo
  dlg.setValue("photo",PropertyUtils.getPropertyNoErr(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,
                                                      "url.photo"));
  if (dlg.getValue("photo")==null)
  { // fill in the "no photo" URL
    globals = vcast.getGlobalPropertiesStore(req);
    url = globals.getObject(VeniceNamespaces.CONTENT_LAF_NAMESPACE,"user.nophoto.url");
    urltype = globals.getObject(VeniceNamespaces.CONTENT_LAF_NAMESPACE,"user.nophoto.url.type");
    rewriter = cast.queryURLRewriter(req);
    dlg.setValue("photo",rewriter.rewriteURL(urltype,url));

  } // end if

  if (admin_flags.get(0))
    dlg.setEnabled("photo",false);

  dlg.setRenderParam("rtgt",stringutils.encodeURL(target));
  vlib.setLocation(req,target);
  vlib.setDisplayLogin(req,false);
  dynamo.scriptReturn(new FrameDialog(dlg));

} // end catch

if (op=="update")
{ // get the user privacy settings
  priv = cast.toOptionSet(user.getObject(VeniceNamespaces.USER_PROFILE_NAMESPACE,"privacy"));

  // poke in all the updates for the user!
  PropertyUtils.setOrRemove(user,user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.prefix",
                            dlg.getValue("prefix"));
  user.setObject(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.given",dlg.getValue("first"));
  s = dlg.getValue("mid");
  if (s!=null)
    user.setObject(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.mi",
                   new Character(s.toString().charAt(0)));
  else
    user.removeObject(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.mi");
  user.setObject(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.family",dlg.getValue("last"));
  PropertyUtils.setOrRemove(user,user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"name.suffix",
                            dlg.getValue("suffix"));
  PropertyUtils.setOrRemove(user,user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"company.name",
                            dlg.getValue("company"));
  PropertyUtils.setOrRemove(user,user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"address.1",
                            dlg.getValue("addr1"));
  PropertyUtils.setOrRemove(user,user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"address.2",
                            dlg.getValue("addr2"));
  priv.set(0,cast.toBoolean(dlg.getValue("pvt_addr")));
  user.setObject(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"locality",dlg.getValue("loc"));
  user.setObject(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"region",dlg.getValue("reg"));
  user.setObject(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"postal.code",dlg.getValue("pcode"));
  user.setObject(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"country",dlg.getValue("country"));
  PropertyUtils.setOrRemove(user,user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"phone.voice",
                            dlg.getValue("phone"));
  priv.set(1,cast.toBoolean(dlg.getValue("pvt_phone")));
  PropertyUtils.setOrRemove(user,user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"phone.mobile",
                            dlg.getValue("mobile"));
  priv.set(2,cast.toBoolean(dlg.getValue("pvt_mobile")));
  PropertyUtils.setOrRemove(user,user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"phone.fax",
                            dlg.getValue("fax"));
  priv.set(3,cast.toBoolean(dlg.getValue("pvt_fax")));
  reverify = user.setEMailAddress(user,dlg.getValue("email"));
  priv.set(4,cast.toBoolean(dlg.getValue("pvt_email")));
  PropertyUtils.setOrRemove(user,user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"url.homepage",
                            dlg.getValue("url"));
  PropertyUtils.setOrRemove(user,user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"description",
                            dlg.getValue("descr"));
  user.setNoSpam(user,cast.toBoolean(dlg.getValue("no_mass_mail")));
  user.setObject(user,VeniceNamespaces.USER_SETTINGS_NAMESPACE,"locale",dlg.getValue("locale"));
  user.setObject(user,VeniceNamespaces.USER_SETTINGS_NAMESPACE,"timezone",dlg.getValue("tz"));
  user.setObject(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"privacy",priv);

  // Set the "profile last updated" date for the user.
  user.setObject(user,VeniceNamespaces.USER_PROFILE_NAMESPACE,"last.update",dynamo.currentDate());

  // Reset the password.
  pass = dlg.getValue("pass1");
  if (stringutils.isNotEmpty(pass1))
  { // set the password and reminder
    user.setAuthenticationData(user,UserInfoNamespace.NAMESPACE,UserInfoNamespace.AUTH_DEFAULT,"",pass);
    PropertyUtils.setOrRemove(user,user,VeniceNamespaces.USER_SETTINGS_NAMESPACE,"password.reminder",
                              dlg.getValue("remind"));

  } // end if

  if (!reverify)  // all done - we can go back where we came from
    dynamo.scriptReturn(new Redirect("SERVLET",target));

  // The user might not need to re-verify - test this
  srm = cast.querySecurityReferenceMonitor(req_help.getRequestObject(Namespaces.DYNAMO_OBJECT_NAMESPACE,
                                                                     "srm"));
  if (srm.getGlobalAcl().testPermission(user,Namespaces.DYNAMO_USER_INFO_NAMESPACE,"bypass.email.verify"))
    dynamo.scriptReturn(new Redirect("SERVLET",target));

  // User needs to be re-verified - generate a new confirmation number
  confnum = vlib.randomConfirmationNumber();
  user.setObject(user,VeniceNamespaces.USER_SETTINGS_NAMESPACE,"confirmation.number",
                 cast.toIntegerObject(confnum));

  // remove us from Verified Users for the nonce
  srm.getVerifiedUsersGroup().removeMember(user);

  // 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,user,VeniceNamespaces.USER_EVENT_NAMESPACE,"send.confirm.email",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 profile.js");
  dynamo.scriptOutput(new ErrorBox("Internal Error","Unknown command button pressed","SERVLET",target));

} // end else
