/*
 * 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): 
 */
package com.silverwrist.venice.servlets.format;

import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.except.*;
import com.silverwrist.venice.security.Role;

public class AdminModifyUserDialog extends ContentDialog
{
  /*--------------------------------------------------------------------------------
   * Constructors
   *--------------------------------------------------------------------------------
   */

  public AdminModifyUserDialog()
  {
    super("Modify User Account",null,"moduserform","sysadmin");
    setHiddenField("cmd","UM");
    setHiddenField("uid","");

    addFormField(new CDFormCategoryHeader("Security Information","To change the user's password, enter a new "
					  + "password into the fields below."));
    addFormField(new CDPasswordFormField("pass1","Password",null,false,32,128));
    addFormField(new CDPasswordFormField("pass2","Password","(retype)",false,32,128));
    addFormField(new CDTextFormField("remind","Password reminder phrase",null,false,32,255));
    addFormField(new CDRoleListFormField("base_lvl","Base security level",null,true,
					 Collections.EMPTY_LIST));
    addFormField(new CDCheckBoxFormField("verify_email","E-mail address verified",null,"Y"));
    addFormField(new CDCheckBoxFormField("lockout","Account locked out",null,"Y"));
    addFormField(new CDFormCategoryHeader("Name"));
    addFormField(new CDTextFormField("prefix","Prefix","(Mr., Ms., etc.)",false,8,8));
    addFormField(new CDTextFormField("first","First name",null,true,32,64));
    addFormField(new CDTextFormField("mid","Middle initial",null,false,1,1));
    addFormField(new CDTextFormField("last","Last name",null,true,32,64));
    addFormField(new CDTextFormField("suffix","Suffix","(Jr., III, etc.)",false,16,16));
    addFormField(new CDFormCategoryHeader("Location"));
    addFormField(new CDTextFormField("company","Company",null,false,32,255));
    addFormField(new CDTextFormField("addr1","Address",null,false,32,255));
    addFormField(new CDTextFormField("addr2","Address","(line 2)",false,32,255));
    addFormField(new CDCheckBoxFormField("pvt_addr","Hide address in profile",null,"Y"));
    addFormField(new CDTextFormField("loc","City",null,true,32,64));
    addFormField(new CDTextFormField("reg","State/Province",null,true,32,64));
    addFormField(new CDTextFormField("pcode","Zip/Postal Code",null,true,32,64));
    addFormField(new CDCountryListFormField("country","Country",null,true));
    addFormField(new CDFormCategoryHeader("Phone Numbers"));
    addFormField(new CDTextFormField("phone","Telephone",null,false,32,32));
    addFormField(new CDTextFormField("mobile","Mobile/cellphone",null,false,32,32));
    addFormField(new CDCheckBoxFormField("pvt_phone","Hide phone/mobile numbers in profile",null,"Y"));
    addFormField(new CDTextFormField("fax","Fax",null,false,32,32));
    addFormField(new CDCheckBoxFormField("pvt_fax","Hide fax number in profile",null,"Y"));
    addFormField(new CDFormCategoryHeader("Internet"));
    addFormField(new CDEmailAddressFormField("email","E-mail address",null,true,32,255));
    addFormField(new CDCheckBoxFormField("pvt_email","Hide e-mail address in profile",null,"Y"));
    addFormField(new CDTextFormField("url","Home page","(URL)",false,32,255));
    addFormField(new CDFormCategoryHeader("Personal"));
    addFormField(new CDTextFormField("descr","Personal description",null,false,32,255));
    addFormField(new CDFormCategoryHeader("User Preferences"));
    addFormField(new CDLocaleListFormField("locale","Default locale","(for formatting dates/times)",true));
    addFormField(new CDTimeZoneListFormField("tz","Default time zone",null,true));
    addCommandButton(new CDImageButton("update","bn_update.gif","Update",80,24));
    addCommandButton(new CDImageButton("cancel","bn_cancel.gif","Cancel",80,24));

  } // end constructor

  protected AdminModifyUserDialog(AdminModifyUserDialog other)
  {
    super(other);

  } // end AdminModifyUserDialog

  /*--------------------------------------------------------------------------------
   * Internal functions
   *--------------------------------------------------------------------------------
   */

  private void coreSetup(AdminOperations ops, AdminUserContext admuser)
  {
    setSubtitle("User: " + admuser.getUserName());
    setHiddenField("uid",String.valueOf(admuser.getUID()));

    CDPickListFormField level_field = (CDPickListFormField)modifyField("base_lvl");
    List role_list = ops.getAllowedRoleList();
    level_field.setChoicesList(role_list);

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

      } // end if

    } // end while

    if (!found)
    { // not in the list - set the defined "role list" to be a singleton of our current level
      role_list = Collections.singletonList(my_role);
      level_field.setChoicesList(role_list);
      
    } // end if

  } // end coreSetup

  /*--------------------------------------------------------------------------------
   * Overrides from class Object
   *--------------------------------------------------------------------------------
   */

  public Object clone()
  {
    return new AdminModifyUserDialog(this);

  } // end clone

  /*--------------------------------------------------------------------------------
   * Overrides from class ContentDialog
   *--------------------------------------------------------------------------------
   */

  protected void validateWholeForm() throws ValidationException
  {
    String pass1 = getFieldValue("pass1");
    String pass2 = getFieldValue("pass2");

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

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

    } // end if

  } // end validateWholeForm

  /*--------------------------------------------------------------------------------
   * External operations
   *--------------------------------------------------------------------------------
   */

  public void setupDialog(AdminOperations ops, AdminUserContext admuser) throws DataException
  {
    coreSetup(ops,admuser);

    setFieldValue("base_lvl",String.valueOf(admuser.getBaseLevel()));
    if (admuser.isEmailVerified())
      setFieldValue("verify_email","Y");
    if (admuser.isLockedOut())
      setFieldValue("lockout","Y");

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

    setFieldValue("prefix",ci.getNamePrefix());
    setFieldValue("first",ci.getGivenName());
    char init = ci.getMiddleInitial();
    if (init!=' ')
      setFieldValue("mid",String.valueOf(init));
    setFieldValue("last",ci.getFamilyName());
    setFieldValue("suffix",ci.getNameSuffix());
    setFieldValue("company",ci.getCompany());
    setFieldValue("addr1",ci.getAddressLine1());
    setFieldValue("addr2",ci.getAddressLine2());
    if (ci.getPrivateAddress())
      setFieldValue("pvt_addr","Y");
    setFieldValue("loc",ci.getLocality());
    setFieldValue("reg",ci.getRegion());
    setFieldValue("pcode",ci.getPostalCode());
    setFieldValue("country",ci.getCountry());
    setFieldValue("phone",ci.getPhone());
    setFieldValue("mobile",ci.getMobile());
    if (ci.getPrivatePhone())
      setFieldValue("pvt_phone","Y");
    setFieldValue("fax",ci.getFax());
    if (ci.getPrivateFax())
      setFieldValue("pvt_fax","Y");
    setFieldValue("email",ci.getEmail());
    if (ci.getPrivateEmail())
      setFieldValue("pvt_email","Y");
    setFieldValue("url",ci.getURL());
    setFieldValue("descr",admuser.getDescription());
    setFieldValue("locale",admuser.getLocale().toString());
    setFieldValue("tz",admuser.getTimeZone().getID());

  } // end setupDialog

  public void doDialog(AdminUserContext admuser) throws ValidationException, DataException
  {
    validate();   // validate the dialog

    final String yes = "Y";                // the "yes" string

    try
    { // reset the base level
      admuser.setBaseLevel(Integer.parseInt(getFieldValue("base_lvl")));

    } // end try
    catch (NumberFormatException nfe)
    { // this shouldn't happen
      throw new InternalStateError("new_level should be an integer - form screwup");

    } // end catch

    // Change the password if applicable.
    String foo = getFieldValue("pass1");
    if (!StringUtil.isStringEmpty(foo))
      admuser.setPassword(foo,getFieldValue("remind"));

    admuser.setEmailVerified(yes.equals(getFieldValue("verify_email")));
    admuser.setLockedOut(yes.equals(getFieldValue("lockout")));

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

    // Reset all the contact info fields.
    ci.setNamePrefix(getFieldValue("prefix"));
    ci.setGivenName(getFieldValue("first"));
    foo = getFieldValue("mid");
    if ((foo==null) || (foo.length()<1))
      ci.setMiddleInitial(' ');
    else
      ci.setMiddleInitial(foo.charAt(0));
    ci.setFamilyName(getFieldValue("last"));
    ci.setNameSuffix(getFieldValue("suffix"));
    ci.setCompany(getFieldValue("company"));
    ci.setAddressLine1(getFieldValue("addr1"));
    ci.setAddressLine2(getFieldValue("addr2"));
    ci.setPrivateAddress(yes.equals(getFieldValue("pvt_addr")));
    ci.setLocality(getFieldValue("loc"));
    ci.setRegion(getFieldValue("reg"));
    ci.setPostalCode(getFieldValue("pcode"));
    ci.setCountry(getFieldValue("country"));
    ci.setPhone(getFieldValue("phone"));
    ci.setMobile(getFieldValue("mobile"));
    ci.setPrivatePhone(yes.equals(getFieldValue("pvt_phone")));
    ci.setFax(getFieldValue("fax"));
    ci.setPrivateFax(yes.equals(getFieldValue("pvt_fax")));
    ci.setEmail(getFieldValue("email"));
    ci.setPrivateEmail(yes.equals(getFieldValue("pvt_email")));
    ci.setURL(getFieldValue("url"));

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

    // Save off the user's description and preferences.
    admuser.setDescription(getFieldValue("descr"));
    admuser.setLocale(International.get().createLocale(getFieldValue("locale")));
    admuser.setTimeZone(TimeZone.getTimeZone(getFieldValue("tz")));

  } // end doDialog

  public void resetOnError(AdminOperations ops, AdminUserContext admuser, String message)
  {
    coreSetup(ops,admuser);
    setErrorMessage(message);
    setFieldValue("pass1",null);
    setFieldValue("pass2",null);

  } // end resetOnError

} // end class AdminModifyUserDialog
