// 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): 

importPackage(java.util);
importPackage(Packages.com.silverwrist.venice.core);
importPackage(Packages.com.silverwrist.venice.except);
importPackage(Packages.com.silverwrist.venice.ui);
importPackage(Packages.com.silverwrist.venice.ui.conf);
importPackage(Packages.com.silverwrist.venice.ui.conf.view);
importPackage(Packages.com.silverwrist.venice.ui.helpers);

// Function which sets the correct conference access level onto each entry of the input list.
function augmentList(conf,list)
{
  var rl = new ArrayList(list.size());
  var it = list.iterator();
  while (it.hasNext())
  { // get the conference level and add it to the UserFound object
    var uf = vlib.castUserFound(it.next());
    var level = conf.getMemberLevel(uf.UID);
    rl.add(uf.createNewLevel(level));

  } // end while

  return rl;

} // end augmentList

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

// get the current conference
currc = new CurrentConference(rinput);
conf = currc.getConference(true,"conf/conferences.js.vs?cc=" + comm.communityID);
on_error = "conf/manage_conf.js.vs?cc=" + comm.communityID + "&conf=" + conf.confID;

if (!(conf.canChangeConference()))
{ // you can't fiddle with this conference
  vlib.output(new ErrorBox("Access Error","You do not have permission to change this conference's membership.",
                           on_error));
  vlib.done();

} // end if

// create the view object
view = new ConfMemberView(rinput.engine.getStdNumSearchResults(),conf);

rc = null;
if ("GET"==rinput.verb)
{ // set up the initial state of the view
  try
  { // get the conference membership list
    mbr_list = conf.getMemberList();
    view.simple = true;
    view.results = mbr_list;
    view.findCount = mbr_list.size();
    rc = view;

  } // end try
  catch (e)
  { // we can get at least one exception here
    etype = vlib.exceptionType(e) + "";
    if (etype.match("DataException"))
      rc = new ErrorBox("Database Error","Database error retrieving membership list: " + e.message,on_error);
    else if (etype.match("AccessError"))
      rc = new ErrorBox("Access Error",e.message,on_error);
    else
      rc = e;

  } // end catch

  vlib.output(rc);
  vlib.done();

} // end if

if (rinput.isImageButtonClicked("update"))
{ // do an update of privileges in this conference
  list_uids = vlib.splitList(rinput.getParameter("listuids"),":");
  try
  { // loop through the defined UIDs and check the level...
    it = list_uids.iterator();
    while (it.hasNext())
    { // get the current and new levels, compare them, and reset if needed
      x = it.next();
      cur_level = rinput.getParameterInt("zxcur_" + x,-1);
      new_level = rinput.getParameterInt("zxnew_" + x,-1);
      if (cur_level!=new_level)
        conf.setMembership(parseInt(x,10),new_level);

    } // end while

  } // end try
  catch (e)
  { // the update might throw an error message
    etype = vlib.exceptionType(e) + "";
    if (etype.match("DataException"))
      rc = new ErrorBox("Database Error","Database error adjusting permissions: " + e.message,on_error);
    else if (etype.match("AccessError"))
      rc = new ErrorBox("Access Error",e.message,on_error);
    else
      rc = e;

    vlib.output(rc);  // bail out now with the error message
    vlib.done();

  } // end catch

} // end if

// Carry on with the search operation now.
try
{ // handle the actual search
  if ("1"==rinput.getParameter("sl"))
  { // Set up some of the easy initial parameters.
    view.simple = true;

    // Retrieve the offset and find count.
    view.offset = rinput.getParameterInt("ofs",0);
    // view.findCount = rinput.getParameterInt("fcount",-1); (N.B.: will get reassigned below)
 
    // Adjust the offset based on the button clicked.
    if (rinput.isImageButtonClicked("search"))
      throw new ValidationException("Invalid button clicked."); // can't happen
    else if (rinput.isImageButtonClicked("previous"))
      view.offset = Math.max(view.offset-view.maxResults,0);
    else if (rinput.isImageButtonClicked("next"))
      view.offset += view.maxResults;
    else if (!(rinput.isImageButtonClicked("update")))
      throw new ValidationException("Unable to determine what action triggered the form.");

    // Get the list and subset it if necessary.
    // N.B.: Since the update function can reduce the size of the member list, we need to take into account
    // that the find count will need updating and the offset may be in the wrong place for the list now.
    mbr_list = conf.getMemberList();
    view.findCount = mbr_list.size();
    while ((view.offset>0) && (view.offset>=view.findCount))
      view.offset = Math.max(view.offset-view.maxResults,0);
    if (view.offset==0)
      view.results = mbr_list;
    else
      view.results = mbr_list.subList(offset,mbr_list.size());

  } // end if
  else
  { // This is a search operation...
    view.simple = false;

    // Get the search field parameter.
    x = rinput.getParameterInt("field",SearchMode.FIELD_USER_NAME);
    if (   (x!=SearchMode.FIELD_USER_NAME) && (x!=SearchMode.FIELD_USER_DESCRIPTION)
        && (x!=SearchMode.FIELD_USER_GIVEN_NAME) && (x!=SearchMode.FIELD_USER_FAMILY_NAME))
      throw new ValidationException("The search field parameter is not valid.");
    view.field = x;

    // Get the search mode parameter.
    x = rinput.getParameterInt("mode",SearchMode.SEARCH_PREFIX);
    if (   (x!=SearchMode.SEARCH_PREFIX) && (x!=SearchMode.SEARCH_SUBSTRING)
        && (x!=SearchMode.SEARCH_REGEXP))
      throw new ValidationException("The search mode parameter is not valid.");
    view.mode = x;

    // Get the search term parameter.
    view.term = rinput.getParameter("term");
    if (view.term==null)
      view.term = "";

    // Retrieve the offset and find count.
    view.offset = rinput.getParameterInt("ofs",0);
    view.findCount = rinput.getParameterInt("fcount",-1);
 
    // Adjust the offset based on the button clicked.
    if (rinput.isImageButtonClicked("search"))
      view.offset = 0;  // begin a new search
    else if (rinput.isImageButtonClicked("previous"))
      view.offset = Math.max(view.offset-view.maxResults,0);
    else if (rinput.isImageButtonClicked("next"))
      view.offset += view.maxResults;
    else if (!(rinput.isImageButtonClicked("update")))
      throw new ValidationException("Unable to determine what action triggered the form.");

    // Perform the search!  (Note that we search on COMMUNITY members, not CONFERENCE members, as this is the
    // way that we add additional members to a conference.)
    tmp_results = comm.searchForMembers(view.field,view.mode,view.term,view.offset,view.maxResults);
    view.results = augmentList(conf,tmp_results);
    if (view.findCount<0)
      view.findCount = comm.getSearchMemberCount(view.field,view.mode,view.term);

  } // end else (search operation)

  rc = view;

} // end try
catch (e)
{ // handle an error in search
  etype = vlib.exceptionType(e) + "";
  if (etype.match("ValidationException"))
    rc = new ErrorBox("Find Error",e.message + " Please try again.",on_error);
  else if (etype.match("DataException"))
    rc = new ErrorBox("Database Error","Database error getting member list: " + e.message,on_error);
  else if (etype.match("AccessError"))
    rc = new ErrorBox("Access Error",e.message,on_error);
  else
    rc = e;

} // end catch

vlib.output(rc);  // all done!
