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

// Get the request object and the target URI.
rinput = bsf.lookupBean("request");
target = rinput.getParameter("tgt");
if (target==null)
  target = "top.js.vs";

// If the user is already logged in, this is an error.
user = rinput.user;
if (user.isLoggedIn())
{ // user already logged in - just bail on this
  vlib.output(new ErrorBox(null,"You cannot create a new account while logged in on an existing one. "
	                   + "You must log out first.",target));
  vlib.done();

} // end if

// create the new account dialog
dlg = rinput.getDialog("newacct");

if ("GET"==rinput.verb)
{ // display the dialog and have done with it
  dlg.setValue("tgt",target);
  rinput.location = target;
  rinput.displayLogin = false;
  vlib.output(dlg);
  vlib.done();

} // end if

// everything that follows is for a POST operation
op = dlg.whichButton(rinput) + "";
if (op=="cancel")
{ // user cancelled create - bounce back to the target
  vlib.output(new Redirect(target,LinkTypes.SERVLET));
  vlib.done();

} // end if

rc = null;
if (op=="create")
{ // we actually want to create the new account
  dlg.load(rinput);

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

    // validate a couple of other issues
    if (!(dlg.getValue("pass1").equals(dlg.getValue("pass2"))))
      throw new ValidationException("The typed passwords do not match.");
    if (rinput.engine.isEmailAddressBanned(dlg.getValue("email")))
      throw new ValidationException("This email address may not register a new account.");

    // Create the new user account and set up its initial context.
    uc = rinput.engine.createNewAccount(rinput.sourceAddress,dlg.getValue("user"),dlg.getValue("pass1"),
                                        dlg.getValue("remind"));

    // Set up the account's contact info.
    ci = uc.getContactInfo();
    ci.namePrefix = dlg.getValue("prefix");
    ci.givenName = dlg.getValue("first");
    blort = dlg.getValue("mid") + "";
    if (blort.length<1)
      ci.middleInitial = " ";
    else
      ci.middleInitial = blort.substring(0,1);
    ci.familyName = dlg.getValue("last");
    ci.nameSuffix = dlg.getValue("suffix");
    ci.locality = dlg.getValue("loc");
    ci.region = dlg.getValue("reg");
    ci.postalCode = dlg.getValue("pcode");
    ci.country = dlg.getValue("country");
    ci.email = dlg.getValue("email");

    // save the contact info for the user (this also sends email confirmation messages as needed)
    uc.putContactInfo(ci);

    // this is now the user for this session!
    sctl = vlib.querySessionControl(rinput);
    sctl.replaceUser(uc);

    // Now bounce us immediately to the Verification dialog.
    rc = new Redirect("verify_email.js.vs?tgt=" + vlib.encodeURL(target),LinkTypes.SERVLET);

  } // end try
  catch (e)
  { // we caught some sort of exception...but what is it?
    etype = vlib.exceptionType(e) + "";
    if (etype.match("ValidationException"))
    { // put the dialog back up on a validation error
      dlg.setErrorMessage(e.message + " Please try again.");
      dlg.setValue("pass1",null);
      dlg.setValue("pass2",null);
      rinput.location = target;
      rinput.displayLogin = false;
      rc = dlg;

    } // end if
    else if (etype.match("DataException"))
      rc = new ErrorBox("Database Error","Database error creating account: " + e.message,target);
    else if (etype.match("AccessError"))
    { // put the dialog back up on an access error
      dlg.setErrorMessage(e.message);
      dlg.setValue("pass1",null);
      dlg.setValue("pass2",null);
      rinput.location = target;
      rinput.displayLogin = false;
      rc = dlg;

    } // end if
    else if (etype.match("EmailException"))
      rc = new ErrorBox("E-mail Error","E-mail error creating account: " + e.message,target);
    else
      rc = e;

  } // end catch

} // end if
else
{ // no dialog present
  logger.error("no known button click on POST to new_account_2.js");
  rc = new ErrorBox("Internal Error","Unknown command button pressed",target);

} // end else

vlib.output(rc);