/*
 * 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.util.*;
import com.silverwrist.util.StringUtil;
import com.silverwrist.venice.security.Role;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.except.*;

public class EditCommunityProfileDialog extends ContentDialog
{
  /*--------------------------------------------------------------------------------
   * The logo URL control class.
   *--------------------------------------------------------------------------------
   */

  static class CDCommunityLogoControl extends CDBaseFormField
  {
    private String linkURL;

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

    protected CDCommunityLogoControl(CDCommunityLogoControl 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.getFullImagePath("sig_other.jpg");
      out.write("<IMG SRC=\"" + photo + "\" ALT=\"\" BORDER=0 WIDTH=110 HEIGHT=65></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 CDCommunityLogoControl(this);

    } // end clone

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

    } // end setLinkURL

  } // end class CDCommunityLogoControl

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

  private static final String YES = "Y";

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

  private CDCommunityLogoControl logo_control;
  private VeniceEngine engine;
  private int cid;

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

  public EditCommunityProfileDialog(SecurityInfo sinf)
  {
    super("Edit Community Profile:",null,"commprofform","sigadmin");
    setHiddenField("cmd","P");
    setHiddenField("sig","");

    Vector vec_pubpriv = new Vector(2);
    vec_pubpriv.add("0|Public");
    vec_pubpriv.add("1|Private");
    vec_pubpriv.trimToSize();

    Vector vec_hidemode = new Vector(3);
    vec_hidemode.add(String.valueOf(CommunityContext.HIDE_NONE) + "|Show in both directory and search");
    vec_hidemode.add(String.valueOf(CommunityContext.HIDE_DIRECTORY)
		     + "|Hide in directory, but not in search");
    vec_hidemode.add(String.valueOf(CommunityContext.HIDE_BOTH) + "|Hide in both directory and search");
    vec_hidemode.trimToSize();

    addFormField(new CDFormCategoryHeader("Basic Information"));
    addFormField(new CDTextFormField("name","Community Name",null,true,32,128));
    addFormField(new CDVeniceIDFormField("alias","Community Alias",null,true,32,32));
    addFormField(new CDTextFormField("synopsis","Synopsis",null,false,32,255));
    addFormField(new CDTextFormField("rules","Rules",null,false,32,255));
    addFormField(new CDLanguageListFormField("language","Primary language",null,true));
    addFormField(new CDTextFormField("url","Home page",null,false,32,255));
    logo_control = new CDCommunityLogoControl("logo","Community logo","commlogo");
    addFormField(logo_control);

    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 CDTextFormField("loc","City",null,false,32,64));
    addFormField(new CDTextFormField("reg","State/Province",null,false,32,64));
    addFormField(new CDTextFormField("pcode","Zip/Postal Code",null,true,32,64));
    addFormField(new CDCountryListFormField("country","Country",null,true));

    addFormField(new CDFormCategoryHeader("Security"));
    addFormField(new CDSimplePickListFormField("comtype","Communty type",null,true,vec_pubpriv,'|'));
    addFormField(new CDTextFormField("joinkey","Join key","(for private communities)",false,32,64));
    addFormField(new CDCheckBoxFormField("membersonly","Allow only members to access this community",
					 null,YES));
    addFormField(new CDSimplePickListFormField("hidemode","Community visibility",null,true,vec_hidemode,'|'));
    addFormField(new CDRoleListFormField("read_lvl","Security level required to read contents",null,true,
					 sinf.getRoleList("Community.Read")));
    addFormField(new CDRoleListFormField("write_lvl","Security level required to update profile",null,true,
					 sinf.getRoleList("Community.Write")));
    addFormField(new CDRoleListFormField("create_lvl","Security level required to create new subobjects",
					 null,true,sinf.getRoleList("Community.Create")));
    addFormField(new CDRoleListFormField("delete_lvl","Security level required to delete community",null,true,
					 sinf.getRoleList("Community.Delete")));
    addFormField(new CDRoleListFormField("join_lvl","Security level required to join community",null,true,
					 sinf.getRoleList("Community.Join")));

    addFormField(new CDFormCategoryHeader("Conferencing Options"));
    addFormField(new CDCheckBoxFormField("pic_in_post","Display user pictures next to posts in conferences",
					 "(by default; user can override)",YES));

    addCommandButton(new CDImageButton("update","bn_update.gif","Update",80,24));
    addCommandButton(new CDImageButton("cancel","bn_cancel.gif","Cancel",80,24));

  } // end EditCommunityProfileDialog

  protected EditCommunityProfileDialog(EditCommunityProfileDialog other)
  {
    super(other);
    logo_control = (CDCommunityLogoControl)modifyField("logo");

  } // end constructor

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

  private void doDisable(CommunityContext comm)
  {
    if (comm.isAdminCommunity())
    { // make sure certain fields are disabled for admin community
      setFieldEnabled("comtype",false);
      setFieldEnabled("joinkey",false);
      setFieldEnabled("membersonly",false);
      setFieldEnabled("hidemode",false);
      setFieldEnabled("read_lvl",false);
      setFieldEnabled("write_lvl",false);
      setFieldEnabled("create_lvl",false);
      setFieldEnabled("delete_lvl",false);
      setFieldEnabled("join_lvl",false);

    } // end if

  } // end doDisable

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

  protected void validateWholeForm() throws ValidationException
  {
    if (engine.aliasExists(getFieldValue("alias"),cid))
      throw new ValidationException("That alias is already used by another community on the system.");

    if (getFieldValue("comtype").equals("1"))
    { // make sure if they flagged it as Private that they specified a join key
      if (StringUtil.isStringEmpty(getFieldValue("joinkey")))
	throw new ValidationException("Private communities must specify a join key value.");

    } // end if

  } // end validateWholeForm

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

  public void setupDialogBasic(VeniceEngine engine, CommunityContext comm)
  {
    this.engine = engine;
    this.cid = comm.getCommunityID();

  } // end setupDialogBasic

  public void setupDialog(VeniceEngine engine, CommunityContext comm) throws DataException, AccessError
  {
    setupDialogBasic(engine,comm);
    ContactInfo ci = comm.getContactInfo();
    CommunityProperties props = comm.getProperties();

    setHiddenField("sig",String.valueOf(comm.getCommunityID()));
    setFieldValue("name",comm.getName());
    setFieldValue("alias",comm.getAlias());
    setFieldValue("synopsis",comm.getSynopsis());
    setFieldValue("rules",comm.getRules());
    setFieldValue("language",comm.getLanguageCode());
    setFieldValue("url",ci.getURL());
    setFieldValue("logo",ci.getPhotoURL());
    logo_control.setLinkURL("commlogo?sig=" + comm.getCommunityID());
    setFieldValue("company",ci.getCompany());
    setFieldValue("addr1",ci.getAddressLine1());
    setFieldValue("addr2",ci.getAddressLine2());
    setFieldValue("loc",ci.getLocality());
    setFieldValue("reg",ci.getRegion());
    setFieldValue("pcode",ci.getPostalCode());
    setFieldValue("country",ci.getCountry());
    if (comm.isPublicCommunity())
    { // public community - no join key
      setFieldValue("comtype","0");
      setFieldValue("joinkey","");

    } // end if
    else
    { // private community - display the join key
      setFieldValue("comtype","1");
      setFieldValue("joinkey",comm.getJoinKey());

    } // end else

    if (comm.getMembersOnly())
      setFieldValue("membersonly",YES);
    setFieldValue("hidemode",String.valueOf(comm.getHideMode()));
    setFieldValue("read_lvl",String.valueOf(comm.getReadLevel()));
    setFieldValue("write_lvl",String.valueOf(comm.getWriteLevel()));
    setFieldValue("create_lvl",String.valueOf(comm.getCreateLevel()));
    setFieldValue("delete_lvl",String.valueOf(comm.getDeleteLevel()));
    setFieldValue("join_lvl",String.valueOf(comm.getJoinLevel()));
    if (props.getDisplayPostPictures())
      setFieldValue("pic_in_post",YES);

    doDisable(comm);

  } // end setupDialog

  public void doDialog(CommunityContext comm) throws ValidationException, DataException, AccessError
  {
    validate();  // validate the dialog entries

    int hidemode, read_lvl, write_lvl, create_lvl, delete_lvl, join_lvl;
    try
    { // convert the values of some dropdowns to real numbers
      hidemode = Integer.parseInt(getFieldValue("hidemode"));
      read_lvl = Integer.parseInt(getFieldValue("read_lvl"));
      write_lvl = Integer.parseInt(getFieldValue("write_lvl"));
      create_lvl = Integer.parseInt(getFieldValue("create_lvl"));
      delete_lvl = Integer.parseInt(getFieldValue("delete_lvl"));
      join_lvl = Integer.parseInt(getFieldValue("join_lvl"));

    } // end try
    catch (NumberFormatException nfe)
    { // how rude!
      throw new InternalStateError("somehow we got a non-numeric result from a numeric dropdown list!");

    } // end catch

    // save off the ContactInfo-related fields first
    ContactInfo ci = comm.getContactInfo();
    ci.setURL(getFieldValue("url"));
    ci.setCompany(getFieldValue("company"));
    ci.setAddressLine1(getFieldValue("addr1"));
    ci.setAddressLine2(getFieldValue("addr2"));
    ci.setLocality(getFieldValue("loc"));
    ci.setRegion(getFieldValue("reg"));
    ci.setPostalCode(getFieldValue("pcode"));
    ci.setCountry(getFieldValue("country"));
    comm.putContactInfo(ci);

    // now save off the property-related fields
    CommunityProperties props = comm.getProperties();
    props.setDisplayPostPictures(YES.equals(getFieldValue("pic_in_post")));
    comm.setProperties(props);

    // now save the big text fields
    comm.setName(getFieldValue("name"));
    comm.setAlias(getFieldValue("alias"));
    comm.setSynopsis(getFieldValue("synopsis"));
    comm.setRules(getFieldValue("rules"));
    comm.setLanguage(getFieldValue("language"));

    if (!(comm.isAdminCommunity()))
    { // save off the security information
      String jkey;
      if (getFieldValue("comtype").equals("1"))
	jkey = getFieldValue("joinkey");
      else
	jkey = null;
      comm.setJoinKey(jkey);
      comm.setMembersOnly(YES.equals(getFieldValue("membersonly")));
      comm.setHideMode(hidemode);
      comm.setSecurityLevels(read_lvl,write_lvl,create_lvl,delete_lvl,join_lvl);

    } // end if

  } // end doDialog

  public void resetOnError(CommunityContext comm, String message)
  {
    setErrorMessage(message);
    doDisable(comm);

  } // end resetOnError

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

  } // end clone

} // end class EditCommunityProfileDialog

