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

importPackage(java.lang);
importClass(Packages.com.silverwrist.dynamo.Namespaces);
importClass(Packages.com.silverwrist.dynamo.UserInfoNamespace);
importPackage(Packages.com.silverwrist.dynamo.except);
importPackage(Packages.com.silverwrist.dynamo.iface);
importPackage(Packages.com.silverwrist.dynamo.security);
importPackage(Packages.com.silverwrist.dynamo.util);
importClass(Packages.com.silverwrist.venice.CommunityVisibility);
importClass(Packages.com.silverwrist.venice.VeniceNamespaces);
importPackage(Packages.com.silverwrist.venice.frame);
importPackage(Packages.com.silverwrist.venice.iface);

req = bsf.lookupBean("request");
req_help = bsf.lookupBean("request_help");
user = vlib.getUser(req);
comm = vlib.getCommunity(req);

// Make sure we are permitted to be here.
acl = comm.getAcl();
if (!(   acl.testPermission(user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"set.property")
      && acl.testPermission(user,VeniceNamespaces.COMMUNITY_PERMS_NAMESPACE,"grant.revoke.access")
      && acl.testPermission(user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"set.visibility")
      && acl.testPermission(user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"set.name")
      && acl.testPermission(user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"set.alias")))
  dynamo.scriptReturn(vlib.stdErrorBox(req,"Security Error",
                                       "You are not permitted to modify this community's profile."));

variable_type = acl.testPermission(user,VeniceNamespaces.COMMUNITY_SECURITY_NAMESPACE,"set.property")

// Create the dialog.
loader = cast.queryDialogLoader(req);
dlg = loader.loadDialogResource("comm/community_profile.dlg.xml");

return_URL = "comm/admin/main.js.vs?cc=" + comm.getCID();   // shortcut

rc = null;
if (req_help.isVerb("GET"))
{ // Load the dialog with its initial values.
  dlg.setValue("cc",comm.getCID() + "");

  dlg.setValue("name",comm.getName());
  dlg.setValue("alias",comm.getAlias());
  dlg.setValue("synopsis",PropertyUtils.getPropertyNoErr(comm,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,
                                                         "synopsis"));
  dlg.setValue("rules",PropertyUtils.getPropertyNoErr(comm,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"rules"));
  dlg.setValue("language",comm.getObject(VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"language"));
  dlg.setValue("url",PropertyUtils.getPropertyNoErr(comm,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"url.homepage"));
  dlg.setValue("logo",PropertyUtils.getPropertyNoErr(comm,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"url.logo"));
  if (dlg.getValue("logo")==null)
  { // fill in the "no logo" URL
    globals = vcast.getGlobalPropertiesStore(req);
    url = globals.getObject(VeniceNamespaces.COMMUNITY_GLOBALS_NAMESPACE,"community.nologo.url");
    urltype = globals.getObject(VeniceNamespaces.COMMUNITY_GLOBALS_NAMESPACE,"community.nologo.url.type");
    rewriter = cast.queryURLRewriter(req);
    dlg.setValue("logo",rewriter.rewriteURL(urltype,url));

  } // end if

  dlg.setValue("company",PropertyUtils.getPropertyNoErr(comm,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,
                                                        "company.name"));
  dlg.setValue("addr1",PropertyUtils.getPropertyNoErr(comm,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"address.1"));
  dlg.setValue("addr2",PropertyUtils.getPropertyNoErr(comm,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"address.2"));
  dlg.setValue("loc",PropertyUtils.getPropertyNoErr(comm,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"locality"));
  dlg.setValue("reg",PropertyUtils.getPropertyNoErr(comm,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"region"));
  dlg.setValue("pcode",comm.getObject(VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"postal.code"));
  dlg.setValue("country",comm.getObject(VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"country"));

  dlg.setValue("comtype",comm.getObject(VeniceNamespaces.COMMUNITY_SECURITY_NAMESPACE,"type.hint"));
  dlg.setValue("joinkey",PropertyUtils.getPropertyNoErr(comm,VeniceNamespaces.COMMUNITY_SECURITY_NAMESPACE,
                                                        "join.key"));
  dlg.setValue("visibility",comm.getVisibility().getName());

} // end if
else
{ // Load information from the dialog
  op = dlg.getClickedButton(req) + "";
  if (op=="cancel")  // user cancelled - bounce back to the previous menu
    rc = new Redirect("SERVLET",return_URL);
  else
  { // load and validate the dialog
    dlg.load(req);
    try
    { // validate the dialog
      dlg.validate(req);

      // set the appropriate values into the community properties
      comm.setName(user,dlg.getValue("name"));
      comm.setAlias(user,dlg.getValue("alias"));
      PropertyUtils.setOrRemove(comm,user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"synopsis",
                                dlg.getValue("synopsis"));
      PropertyUtils.setOrRemove(comm,user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"rules",dlg.getValue("rules"));
      comm.setObject(user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"language",dlg.getValue("language"));
      PropertyUtils.setOrRemove(comm,user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"url.homepage",
                                dlg.getValue("url"));
      // N.B.: community logo is handled elsewhere

      PropertyUtils.setOrRemove(comm,user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"company.name",
                                dlg.getValue("company"));
      PropertyUtils.setOrRemove(comm,user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"address.1",
                                dlg.getValue("addr1"));
      PropertyUtils.setOrRemove(comm,user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"address.2",
                                dlg.getValue("addr2"));
      PropertyUtils.setOrRemove(comm,user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"locality",
                                dlg.getValue("loc"));
      PropertyUtils.setOrRemove(comm,user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"region",
                                dlg.getValue("reg"));
      comm.setObject(user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"postal.code",dlg.getValue("pcode"));
      comm.setObject(user,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,"country",dlg.getValue("country"));

      if (variable_type)
      { // see if the community type is changing, set a join key if it is
        old_comtype = cast.toInteger(comm.getObject(VeniceNamespaces.COMMUNITY_SECURITY_NAMESPACE,"type.hint"));
        new_comtype = cast.toInteger(dlg.getValue("comtype"));
        if (old_comtype!=new_comtype)
        { // "Community type" mainly affects the authentication required for the "All Verified Users" group.
          srm = cast.querySecurityReferenceMonitor(req_help.getRequestObject(Namespaces.DYNAMO_OBJECT_NAMESPACE,
                                                   "srm"));
          the_group = srm.getVerifiedUsersGroup();

          switch (new_comtype)
          {
            case 0:  // public access
              comm.grantAccess(user,the_group,null,null,null,null,false);
              if (PropertyUtils.hasProperty(comm,VeniceNamespaces.COMMUNITY_SECURITY_NAMESPACE,"join.key"))
                comm.removeObject(user,VeniceNamespaces.COMMUNITY_SECURITY_NAMESPACE,"join.key");
              break;

            case 1:  // private access
              jkey = dlg.getValue("joinkey");
              comm.grantAccess(user,the_group,UserInfoNamespace.NAMESPACE,UserInfoNamespace.AUTH_DEFAULT,"",
                               jkey,false);
              PropertyUtils.setOrRemove(comm,user,VeniceNamespaces.COMMUNITY_SECURITY_NAMESPACE,"join.key",jkey);
              break;

            case 2:  // invitation-only access
              comm.revokeAccess(user,the_group);
              if (PropertyUtils.hasProperty(comm,VeniceNamespaces.COMMUNITY_SECURITY_NAMESPACE,"join.key"))
                comm.removeObject(user,VeniceNamespaces.COMMUNITY_SECURITY_NAMESPACE,"join.key");
              break;

          } // end switch

          // save off the new type
          comm.setObject(user,VeniceNamespaces.COMMUNITY_SECURITY_NAMESPACE,"type.hint",
                         cast.toIntegerObject(new_comtype));

        } // end if

      } // end if

      comm.setVisibility(user,CommunityVisibility.getEnum(dlg.getValue("visibility")));

      vlib.forceReloadMenu(req);  // the menu might have changed, so reload it

      // All done - bounce back to the main admin menu
      rc = new Redirect("SERVLET",return_URL);

    } // end try
    catch (e)
    { // get the exception type and check it out
      etype = dynamo.exceptionType(e) + "";
      logger.error("Caught exception of type " + etype);
      if (etype.match(/ValidationException/))
      { // validation error...
        dlg.setErrorMessage(dynamo.exceptionMessage(e) + " Please try again.");

        // have to re-prep the community logo
        dlg.setValue("logo",PropertyUtils.getPropertyNoErr(comm,VeniceNamespaces.COMMUNITY_PROFILE_NAMESPACE,
                                                           "url.logo"));
        if (dlg.getValue("logo")==null)
        { // fill in the "no logo" URL
          globals = vcast.getGlobalPropertiesStore(req);
          url = globals.getObject(VeniceNamespaces.COMMUNITY_GLOBALS_NAMESPACE,"community.nologo.url");
          urltype = globals.getObject(VeniceNamespaces.COMMUNITY_GLOBALS_NAMESPACE,"community.nologo.url.type");
          rewriter = cast.queryURLRewriter(req);
          dlg.setValue("logo",rewriter.rewriteURL(urltype,url));

        } // end if

      } // end if
      else if (etype.match(/DatabaseException/))
        rc = new ErrorBox("Database Error",e,"SERVLET",return_URL);
      else if (etype.match(/DynamoSecurityException/))
        rc = new ErrorBox("Security Error",e,"SERVLET",return_URL);
      else
        rc = new ErrorBox("Unknown Exception",e,"SERVLET",return_URL);

    } // end catch

  } // end else
  
} // end else

if (rc==null)
{ // output dialog if we don't have another value
  dlg.setSubtitle(comm.getName());
  dlg.setRenderParam("cid",comm.getCID() + "");
  if (!variable_type)
  { // disable "community type" and "join key"
    dlg.setEnabled("comtype",false);
    dlg.setEnabled("joinkey",false);

  } // end if

  rc = new FrameDialog(dlg);
  rc.menuSelector = "community";

} // end if

dynamo.scriptOutput(rc);
