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

// 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 script is a no-op - just bounce to the specified target.
user = rinput.user;
if (user.isLoggedIn())
{ // user already logged in - just bail on this
  vlib.output(new Redirect(target,LinkTypes.SERVLET));
  vlib.done();

} // end if

// Test to see if the IP address has been banned.
banmsg = rinput.engine.testIPBan(rinput.sourceAddress);
if (banmsg!=null)
{ // this IP address has been banned - you are Not Allowed
  vlib.output(new ErrorBox("This IP address has been banned",banmsg,target));
  vlib.done();

} // end if

dlg = rinput.getDialog("login");

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

} // end if

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

} // end if

dlg.load(rinput);        // load the dialog parameters
rc = null;               // return from this script
if (op=="remind")
{ // send the login reminder
  try
  { // perform the reminder operation
    rinput.engine.sendPasswordReminder(dlg.getValue("user"));

    // recycle the dialog and output it again
    dlg.setErrorMessage("Password reminder has been sent to your e-mail address.");
    dlg.setValue("pass",null);
    rinput.location = target;
    rc = dlg;

  } // end try
  catch (e)
  { // caught an exception here - what do we do about it?
    etype = vlib.exceptionType(e) + "";
    if (etype.match("DataException"))
      rc = new ErrorBox("Database Error","Database error finding user: " + e.getMessage(),target);
    else if (etype.match("AccessError"))
      rc = new ErrorBox("User E-mail Address Not Found",e.getMessage(),target);
    else if (etype.match("EmailException"))
      rc = new ErrorBox("E-mail Error","E-mail error sending reminder: " + e.getMessage(),target);
    else
      rc = e;

  } // end catch

} // end if
else if (op=="login")
{ // actually log in!
  try
  { // authenticate the user
    user.authenticate(dlg.getValue("user"),dlg.getValue("pass"));

    logger.debug("User \"" + user.userName + "\" logged in successfully");

    if (dlg.getValue("saveme").booleanValue())
    { // If the user wants a cookie, give it to them!
      cctl = vlib.queryCookieControl(rinput);
      cctl.savePersistentCookie(rinput.getConfigProperty("login.cookie"),user.getAuthenticationToken(),
                                vlib.toInteger(rinput.getConfigProperty("login.cookie.age")));

    } // end if

    // Clear the left menus (to force recomputation) and bounce us back to whereever we were
    // supposed to go.
    logger.debug("Ready to bounce to \"" + target + "\"");
    rinput.setSessionAttribute(RequestInput.LEFT_MENU_SESSION_ATTR,null);
    if (user.isEmailVerified())
      rc = new Redirect(target,LinkTypes.SERVLET);
    else  // jump to the Verify dialog before we do anything else
      rc = new Redirect("verify_email.js.vs?tgt=" + vlib.encodeURL(target),LinkTypes.SERVLET);

  } // end try
  catch (e)
  { // caught an exception here - what do we do about it?
    etype = vlib.exceptionType(e) + "";
    if (etype.match("DataException"))
      rc = new ErrorBox("Database Error","Database error logging in: " + e.message,target);
    else if (etype.match("AccessError"))
    { // this indicates a problem with the user account or password
      dlg.setErrorMessage(e.message);
      dlg.setValue("pass",null);
      rinput.location = target;
      rc = dlg;

    } // end else if
    else
      rc = e;

  } // end catch

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

} // end else

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