/*
 * 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.io.*;
import java.net.URLEncoder;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.except.*;

public class EditProfileDialog extends ContentDialog
{
  /*--------------------------------------------------------------------------------
   * The photo URL control class.
   *--------------------------------------------------------------------------------
   */

  static class CDUserPhotoControl extends CDBaseFormField
  {
    private String linkURL;

    public CDUserPhotoControl(String name, String caption, String linkURL)
    {
      super(name,caption,"(click to change)",false);
      this.linkURL = linkURL;
      
    } // end constructor

    protected CDUserPhotoControl(CDUserPhotoControl other)
    {
      super(other);
      this.linkURL = other.linkURL;

    } // end constructor

    protected void renderActualField(Writer out, RenderData rdat) throws IOException
    {
      if (isEnabled())
	out.write("<A HREF=\"" + rdat.getEncodedServletPath(linkURL) + "\">");
      String photo = getValue();
      if (StringUtil.isStringEmpty(photo))
	photo = rdat.getPhotoNotAvailURL();
      out.write("<IMG SRC=\"" + photo + "\" ALT=\"\" BORDER=0 WIDTH=100 HEIGHT=100></A>");
      if (isEnabled())
	out.write("</A>");

    } // end renderActualField

    protected void validateContents(String value) throws ValidationException
    { // this is a do-nothing value
    } // end validateContents

    public CDFormField duplicate()
    {
      return new CDUserPhotoControl(this);

    } // end clone

    public void setLinkURL(String s)
    {
      linkURL = s;

    } // end setLinkURL

  } // end class CDUserPhotoControl

  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  private static final String YES = "Y";

  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private CDUserPhotoControl photo_control;

  /*--------------------------------------------------------------------------------
   * Constructors
   *--------------------------------------------------------------------------------
   */

  public EditProfileDialog()
  {
    super("Edit Your Profile",null,"profform","account");
    setHiddenField("cmd","P");
    setHiddenField("tgt","");
    addFormField(new CDFormCategoryHeader("Password","To change your 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 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,YES));
    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,YES));
    addFormField(new CDTextFormField("fax","Fax",null,false,32,32));
    addFormField(new CDCheckBoxFormField("pvt_fax","Hide fax number in profile",null,YES));
    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,YES));
    addFormField(new CDTextFormField("url","Home page","(URL)",false,32,255));
    addFormField(new CDFormCategoryHeader("Personal"));
    addFormField(new CDTextFormField("descr","Personal description",null,false,32,255));
    photo_control = new CDUserPhotoControl("photo","User Photo","userphoto");
    addFormField(photo_control);
    addFormField(new CDFormCategoryHeader("User Preferences"));
    addFormField(new CDCheckBoxFormField("pic_in_post","Display user photos next to conference posts",
					 "(where applicable)",YES));
    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 EditProfileDialog(EditProfileDialog other)
  {
    super(other);
    photo_control = (CDUserPhotoControl)modifyField("photo");

  } // end constructor

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

  public Object clone()
  {
    return new EditProfileDialog(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 setTarget(String target)
  {
    setHiddenField("tgt",target);

  } // end setTarget

  public void setupDialog(UserContext uc, String target) throws DataException
  {
    setTarget(target);
    ContactInfo ci = uc.getContactInfo();  // get the main contact info
    UserProperties props = uc.getProperties();  // get the properties

    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",YES);
    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",YES);
    setFieldValue("fax",ci.getFax());
    if (ci.getPrivateFax())
      setFieldValue("pvt_fax",YES);
    setFieldValue("email",ci.getEmail());
    if (ci.getPrivateEmail())
      setFieldValue("pvt_email",YES);
    setFieldValue("url",ci.getURL());
    setFieldValue("descr",uc.getDescription());
    setFieldValue("photo",ci.getPhotoURL());
    photo_control.setLinkURL("userphoto?tgt=" + URLEncoder.encode(target));
    if (props.getDisplayPostPictures())
      setFieldValue("pic_in_post",YES);
    setFieldValue("locale",uc.getLocale().toString());
    setFieldValue("tz",uc.getTimeZone().getID());

  } // end setupDialog

  public boolean doDialog(UserContext uc) throws ValidationException, DataException, EmailException
  {
    validate();   // validate the dialog

    ContactInfo ci = uc.getContactInfo();  // get the main contact info
    UserProperties props = uc.getProperties();

    // Reset all the contact info fields.
    ci.setNamePrefix(getFieldValue("prefix"));
    ci.setGivenName(getFieldValue("first"));
    String 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.
    boolean retval = uc.putContactInfo(ci);

    // Save off the properties.
    props.setDisplayPostPictures(YES.equals(getFieldValue("pic_in_post")));
    uc.setProperties(props);

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

    // Finally, change the password if applicable.
    foo = getFieldValue("pass1");
    if (!StringUtil.isStringEmpty(foo))
      uc.setPassword(foo,getFieldValue("remind"));

    return retval;  // pass back up so we can decide where to jump

  } // end doDialog

  public void resetOnError(String message)
  {
    setErrorMessage(message);
    setFieldValue("pass1",null);
    setFieldValue("pass2",null);

  } // end resetOnError

} // end class EditProfileDialog
