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

importPackage(java.util);
importPackage(Packages.com.silverwrist.venice.core);
importPackage(Packages.com.silverwrist.venice.except);
importPackage(Packages.com.silverwrist.venice.ui);
importPackage(Packages.com.silverwrist.venice.ui.dlg);
importPackage(Packages.com.silverwrist.venice.ui.helpers);

function setupDialog(dlg,adm,user)
{
  dlg.setSubtitle("User: " + user.userName);
  var role_list = adm.getAllowedRoleList();
  dlg.sendMessage("base_lvl","setRoleList",role_list);

  // See if this level was found on the list.
  var my_role = user.baseRole;
  var found = false;
  var it = role_list.iterator();
  while (it.hasNext())
  { // seek each role in turn
    var r = it.next();
    if (r.equals(my_role))
    { // found it!
      found = true;
      break;

    } // end if

  } // end while

  if (!found)  // role not found - set the defined role list to be a singleton
    dlg.sendMessage("base_lvl","setRoleList",Collections.singletonList(my_role));
  dlg.sendMessage("photo","setLinkURL","sysadmin/modify_photo.js.vs?uid=" + admuser.UID);

} // end setupDialog

rinput = bsf.lookupBean("request");

if (!(rinput.user.hasAdminAccess()))
{ // no admin access - we can't do this
  vlib.output(new ErrorBox("Access Error","You do not have permission to administer the system.",null));
  vlib.done();

} // end if

dlg = rinput.getDialog("admin.modify.user");

rc = null;
if ("GET"==rinput.verb)
{ // set up the dialog
  uid = rinput.getParameterInt("uid",0);
  if (uid==0)
  { // user ID not found
    vlib.output(new ErrorBox(null,"User ID parameter not found.","sysadmin/find_user.js.vs"));
    vlib.done();

  } // end if

  try
  { // load the user's data and populate the dialog box
    adm = rinput.user.adminInterface;
    admuser = adm.getUserContext(uid);
    setupDialog(dlg,adm,admuser);  // set up the dialog box
    dlg.setValue("uid",admuser.UID);

    dlg.setValue("base_lvl",admuser.baseLevel);
    if (admuser.isEmailVerified())
      dlg.setValue("verify_email",1);
    if (admuser.isLockedOut())
      dlg.setValue("lockout",1);

    ci = admuser.getContactInfo();  // get the main contact info
    props = admuser.properties;

    if (props.disallowPhoto)
      dlg.setValue("nophoto",1);
    dlg.setValue("prefix",ci.namePrefix);
    dlg.setValue("first",ci.givenName);
    if (ci.middleInitial!=' ')
      dlg.setValue("mid",String.fromCharCode(ci.middleInitial));
    dlg.setValue("last",ci.familyName);
    dlg.setValue("suffix",ci.nameSuffix);
    dlg.setValue("company",ci.company);
    dlg.setValue("addr1",ci.addressLine1);
    dlg.setValue("addr2",ci.addressLine2);
    if (ci.privateAddress)
      dlg.setValue("pvt_addr",1);
    dlg.setValue("loc",ci.locality);
    dlg.setValue("reg",ci.region);
    dlg.setValue("pcode",ci.postalCode);
    dlg.setValue("country",ci.country);
    dlg.setValue("phone",ci.phone);
    dlg.setValue("mobile",ci.mobile);
    if (ci.privatePhone)
      dlg.setValue("pvt_phone",1);
    dlg.setValue("fax",ci.fax);
    if (ci.privateFax)
      dlg.setValue("pvt_fax",1);
    dlg.setValue("email",ci.email);
    if (ci.privateEmail)
      dlg.setValue("pvt_email",1);
    dlg.setValue("url",ci.URL);
    dlg.setValue("descr",admuser.description);
    dlg.setValue("photo",ci.photoURL);
    if (props.displayPostPictures)
      dlg.setValue("pic_in_post",1);
    if (props.massMailOptOut)
      dlg.setValue("no_mass_mail",1);
    dlg.setValue("locale",admuser.locale);
    dlg.setValue("tz",admuser.timeZone);

    rc = dlg;

  } // end try
  catch (e)
  { // exception initializing dialog
    etype = vlib.exceptionType(e) + "";
    if (etype.match("DataException"))
      rc = new ErrorBox("Database Error","Unable to retrieve user information: " + e.message,
			"sysadmin/find_user.js.vs");
    else if (etype.match("AccessError"))
      rc = new ErrorBox("Access Error","You do not have permission to administer the system.",null);
    else
      rc = e;

  } // end catch

  vlib.output(rc);
  vlib.done();

} // end if

// everything that follows is for a POST operation
op = dlg.whichButton(rinput) + "";
if (op=="cancel")
{ // user cancelled profile update - bounce back to the target
  vlib.output(new Redirect("sysadmin/find_user.js.vs",LinkTypes.SERVLET));
  vlib.done();

} // end if

dlg.load(rinput);        // load the dialog parameters

if (op=="update")
{ // we're updating the user
  try
  { // get the admin interface and the user information
    uid = parseInt(dlg.getValue("uid"),10);
    adm = rinput.user.adminInterface;
    admuser = adm.getUserContext(uid);

    try
    { // validate the dialog
      dlg.validate();

      // check the passwords
      pass1 = dlg.getValue("pass1") + "";
      pass2 = dlg.getValue("pass2") + "";

      if (vlib.emptyString(pass1))
      { // empty must match empty
        if (!(vlib.emptyString(pass2)))
	  throw new ValidationException("The typed passwords do not match.");

      } // end if
      else
      { // the two passwords must match
        if (pass1!=pass2)
	  throw new ValidationException("The typed passwords do not match.");

      } // end else

      // reset the base level
      admuser.baseLevel = dlg.getValue("base_lvl").intValue();

      // Change the password if applicable.
      if (!(vlib.emptyString(pass1)))
        admuser.setPassword(pass1,dlg.getValue("remind"));

      admuser.setEmailVerified(dlg.getValue("verify_email").booleanValue());
      admuser.setLockedOut(dlg.getValue("lockout").booleanValue());

      ci = admuser.getContactInfo();  // get the main contact info
      props = admuser.properties;

      // Reset all the contact info fields.
      props.disallowPhoto = dlg.getValue("nophoto").booleanValue();
      ci.namePrefix = dlg.getValue("prefix");
      ci.givenName = dlg.getValue("first");
      blort = dlg.getValue("mid") + "";
      if (blort.length<1)
        ci.middleInitial = " ";
      else
        ci.middleInitial = blort.substring(0,1);
      ci.familyName = dlg.getValue("last");
      ci.nameSuffix = dlg.getValue("suffix");
      ci.company = dlg.getValue("company");
      ci.addressLine1 = dlg.getValue("addr1");
      ci.addressLine2 = dlg.getValue("addr2");
      ci.privateAddress = dlg.getValue("pvt_addr").booleanValue();
      ci.locality = dlg.getValue("loc");
      ci.region = dlg.getValue("reg");
      ci.postalCode = dlg.getValue("pcode");
      ci.country = dlg.getValue("country");
      ci.phone = dlg.getValue("phone");
      ci.mobile = dlg.getValue("mobile");
      ci.privatePhone = dlg.getValue("pvt_phone").booleanValue();
      ci.fax = dlg.getValue("fax");
      ci.privateFax = dlg.getValue("pvt_fax").booleanValue();
      ci.email = dlg.getValue("email");
      ci.privateEmail = dlg.getValue("pvt_email").booleanValue();
      ci.URL = dlg.getValue("url");
      props.displayPostPictures = dlg.getValue("pic_in_post").booleanValue();
      props.massMailOptOut = dlg.getValue("no_mass_mail").booleanValue();

      // Store the completed contact info.
      admuser.putContactInfo(ci);
      admuser.properties = props;

      // Save off the user's description and preferences.
      admuser.description = dlg.getValue("descr");
      admuser.locale = dlg.getValue("locale");
      admuser.timeZone = dlg.getValue("tz");

      // redirect back to the Find User page
      rc = new Redirect("sysadmin/find_user.js.vs",LinkTypes.SERVLET);

    } // end try
    catch (e)
    { // catch ValidationExceptions here and redisplay the dialog
      etype = vlib.exceptionType(e) + "";
      if (etype.match("ValidationException"))
      { // on a ValidationException, redisplay the dialog and try again
        dlg.setErrorMessage(e.message + " Please try again.");
        setupDialog(dlg,adm,admuser);  // set up the dialog box
        dlg.setValue("pass1",null);
        dlg.setValue("pass2",null);
        rc = dlg;

      } // end if
      else  // propagate other types of exceptions
        throw e;

    } // end catch

  } // end try
  catch (e)
  { // this is used to catch the hard exceptions
    etype = vlib.exceptionType(e) + "";
    if (etype.match("AccessError"))
      rc = new ErrorBox("Access Error","You do not have permission to administer the system.",null);
    else if (etype.match("DataException"))
      rc = new ErrorBox("Database Error","Unable to retrieve user information: " + e.message,
                        "sysadmin/find_user.js.vs");
    else
      rc = e;

  } // end catch

} // end if
else
{ // bogus button indicated
  logger.error("no known button click on POST to sysadmin/modify_user.js");
  rc = new ErrorBox("Internal Error","Unknown command button pressed","sysadmin/find_user.js.vs");

} // end else

vlib.output(rc);  // all done!
