// 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@ricochet.com>,
// for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
// Copyright (C) 2001-2004 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
// 
// Contributor(s): 

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);

// Define a simple function to set up the dialog stuff.
function setupDialog(dlg,comm)
{
  dlg.setSubtitle(comm.name);
  dlg.sendMessage("logo","setLinkURL","comm/photo.js.vs?cc=" + comm.communityID);
  sinf = comm.securityInfo;
  dlg.sendMessage("read_lvl","setRoleList",sinf.getRoleList("Community.Read"));
  dlg.sendMessage("write_lvl","setRoleList",sinf.getRoleList("Community.Write"));
  dlg.sendMessage("create_lvl","setRoleList",sinf.getRoleList("Community.Create"));
  dlg.sendMessage("delete_lvl","setRoleList",sinf.getRoleList("Community.Delete"));
  dlg.sendMessage("join_lvl","setRoleList",sinf.getRoleList("Community.Join"));

  if (comm.isAdminCommunity())
  { // need to disable a bunch of crap if this is the admin community
    dlg.setEnabled("comtype",false);
    dlg.setEnabled("joinkey",false);
    dlg.setEnabled("membersonly",false);
    dlg.setEnabled("hidemode",false);
    dlg.setEnabled("read_lvl",false);
    dlg.setEnabled("write_lvl",false);
    dlg.setEnabled("create_lvl",false);
    dlg.setEnabled("delete_lvl",false);
    dlg.setEnabled("join_lvl",false);

  } // end if

} // end setupDialog

// get the request object and the community
rinput = bsf.lookupBean("request");
comm = rinput.getCommunity(true,"top.js.vs");

if (!(comm.canModifyProfile()))
{ // no access - sorry, dude
  logger.error("tried to call up community profile screen without access...naughty naughty!");
  vlib.output(new ErrorBox("Unauthorized","You do not have access to modify this community's profile.",
			   "comm/admin_menu.js.vs?cc=" + comm.communityID));
  vlib.done();

} // end if

dlg = rinput.getDialog("community.profile");

rc = null;
if ("GET"==rinput.verb)
{ // set up the dialog and return
  setupDialog(dlg,comm);
  dlg.setValue("cc",comm.communityID + "");

  try
  { // load the parameters of the dialog
    ci = comm.getContactInfo();
    props = comm.properties;
    dlg.setValue("name",comm.name);
    dlg.setValue("alias",comm.alias);
    dlg.setValue("synopsis",comm.synopsis);
    dlg.setValue("rules",comm.rules);
    dlg.setValue("language",comm.getLanguageCode());
    dlg.setValue("url",ci.URL);
    dlg.setValue("logo",ci.photoURL);
    dlg.setValue("company",ci.company);
    dlg.setValue("addr1",ci.addressLine1);
    dlg.setValue("addr2",ci.addressLine2);
    dlg.setValue("loc",ci.locality);
    dlg.setValue("reg",ci.region);
    dlg.setValue("pcode",ci.postalCode);
    dlg.setValue("country",ci.country);
    if (comm.isPublicCommunity())
    { // public community - has no join key
      dlg.setValue("comtype","0");
      dlg.setValue("joinkey","");

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

    } // end else

    if (comm.membersOnly)
      dlg.setValue("membersonly",1);
    logger.debug("Community's hidemode is " + comm.hideMode);
    dlg.setValue("hidemode",comm.hideMode);
    dlg.setValue("read_lvl",comm.readLevel);
    dlg.setValue("write_lvl",comm.writeLevel);
    dlg.setValue("create_lvl",comm.createLevel);
    dlg.setValue("delete_lvl",comm.deleteLevel);
    dlg.setValue("join_lvl",comm.joinLevel);
    if (props.displayPostPictures)
      dlg.setValue("pic_in_post",1);

    rc = dlg;

  } // end try
  catch (e)
  { // exception in dialog initialization
    etype = vlib.exceptionType(e) + "";
    if (etype.match("DataException"))
      rc = new ErrorBox("Database Error","Database error retrieving profile: " + e.message,
                        "comm/admin_menu.js.vs?cc=" + comm.communityID);
    else if (etype.match("AccessError"))
      rc = new ErrorBox("Unauthorized","You do not have access to modify this community's profile.",
			"comm/admin_menu.js.vs?cc=" + comm.communityID);
    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("comm/admin_menu.js.vs?cc=" + comm.communityID,LinkTypes.SERVLET));
  vlib.done();

} // end if

if (op=="update")
{ // OK, we can update the dialog!
  dlg.load(rinput);        // load the dialog parameters

  try
  { // start by validating the dialog
    dlg.validate();

    // validate some other stuff we didn't pick up in the fixed validation
    if (rinput.engine.aliasExists(dlg.getValue("alias"),comm.communityID))
      throw new ValidationException("That alias is already used by another community on the system.");

    if ("1"==dlg.getValue("comtype"))
    { // make sure if they flagged it as Private that they specified a join key
      if (vlib.emptyString(dlg.getValue("joinkey")))
	throw new ValidationException("Private communities must specify a join key value.");

    } // end if

    // save off the ContactInfo-related fields first
    ci = comm.getContactInfo();
    ci.URL = dlg.getValue("url");
    ci.company = dlg.getValue("company");
    ci.addressLine1 = dlg.getValue("addr1");
    ci.addressLine2 = dlg.getValue("addr2");
    ci.locality = dlg.getValue("loc");
    ci.region = dlg.getValue("reg");
    ci.postalCode = dlg.getValue("pcode");
    ci.country = dlg.getValue("country");
    comm.putContactInfo(ci);

    // now save off the property-related fields
    props = comm.properties;
    props.displayPostPictures = dlg.getValue("pic_in_post").booleanValue();
    comm.properties = props;

    // now save the big text fields
    comm.name = dlg.getValue("name");
    comm.alias = dlg.getValue("alias");
    comm.synopsis = dlg.getValue("synopsis");
    comm.rules = dlg.getValue("rules");
    comm.setLanguage(dlg.getValue("language"));

    if (!(comm.isAdminCommunity()))
    { // save off the security information
      if ("1"==dlg.getValue("comtype"))
        comm.joinKey = dlg.getValue("joinkey");
      else
        comm.joinKey = null;

      comm.membersOnly = dlg.getValue("membersonly").booleanValue();
      comm.setHideMode(dlg.getValue("hidemode"));
      comm.setSecurityLevels(parseInt(dlg.getValue("read_lvl"),10),parseInt(dlg.getValue("write_lvl"),10),
                             parseInt(dlg.getValue("create_lvl"),10),parseInt(dlg.getValue("delete_lvl"),10),
                             parseInt(dlg.getValue("join_lvl"),10));

    } // end if

    // bounce back to the admin menu
    rinput.setSessionAttribute(RequestInput.LEFT_MENU_SESSION_ATTR,null);
    rc = new Redirect("comm/admin_menu.js.vs?cc=" + comm.communityID,LinkTypes.SERVLET);

  } // end try
  catch (e)
  { // exception setting the profile
    etype = vlib.exceptionType(e) + "";
    if (etype.match("ValidationException"))
    { // validation error - redisplay the dialog
      dlg.setErrorMessage(e.message + " Please try again.");
      setupDialog(dlg,comm);
      rc = dlg;

    } // end if
    else if (etype.match("DataException"))
      rc = new ErrorBox("Database Error","Database error updating community: " + e.message,
			"comm/admin_menu.js.vs?cc=" + comm.communityID);
    else if (etype.match("AccessError"))
      rc = new ErrorBox("Access Error",e.message,"comm/admin_menu.js.vs?cc=" + comm.communityID);
    else
      rc = e;

  } // end catch

} // end try
else
{ // what the hell was that button?
  logger.error("no known button click on POST to comm/profile.js");
  rc = new ErrorBox("Internal Error","Unknown command button pressed",
                    "comm/admin_menu.js.vs?cc=" + comm.communityID);

} // end else

vlib.output(rc);
