/*
 * 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) 2002-03 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.venice.script;

import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.Namespaces;
import com.silverwrist.dynamo.db.UserManagement;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;
import com.silverwrist.venice.VeniceNamespaces;
import com.silverwrist.venice.content.*;
import com.silverwrist.venice.session.SessionInfoParams;

public class LibraryVenice
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  public static final int CONFIRM_MIN = 1000000;
  public static final int CONFIRM_MAX = 9999999;

  private static final String ALPHABET =
      "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./";
  private static final char[] ALPHA_ARRAY = ALPHABET.toCharArray();

  private static final String[] SYLLABARY = {
    "ba", "be", "bi", "bo", "bu",
    "da", "de", "di", "do", "du",
    "cha", "chi", "cho", "chu",
    "fa", "fe", "fi", "fo", "fu",
    "ga", "ge", "gi", "go", "gu",
    "ha", "he", "hi", "ho", "hu",
    "ja", "je", "ji", "jo", "ju",
    "ka", "ke", "ki", "ko", "ku",
    "la", "le", "li", "lo", "lu",
    "ma", "me", "mi", "mo", "mu",
    "na", "ne", "ni", "no", "nu",
    "pa", "pe", "pi", "po", "pu",
    "ra", "re", "ri", "ro", "ru",
    "sa", "se", "si", "so", "su",
    "sha", "she", "sho", "shu",
    "ta", "te", "ti", "to", "tu",
    "va", "ve", "vi", "vo", "vu",
    "wa", "we", "wi", "wo", "wu",
    "ya", "ye", "yi", "yo", "yu",
    "za", "ze", "zi", "zo", "zu"
  };  // 98 syllables

  private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private Random m_rng;

  /*--------------------------------------------------------------------------------
   * Constructor
   *--------------------------------------------------------------------------------
   */

  public LibraryVenice()
  {
    m_rng = new Random();

  } // end constructor

  /*--------------------------------------------------------------------------------
   * External operations
   *--------------------------------------------------------------------------------
   */

  public String dialogFrameTitle(Dialog dlg)
  {
    String s = dlg.getSubtitle();
    if (s==null)
      return dlg.getTitle();
    StringBuffer buf = new StringBuffer(dlg.getTitle());
    buf.append(" - ").append(s);
    return buf.toString();

  } // end dialogFrameTitle

  public String getLocation(Request req)
  {
    return (String)(req.getObject(SessionInfoParams.REQ_NAMESPACE,SessionInfoParams.RATTR_LOCATION));

  } // end getLocation

  public DynamoUser getUser(SessionInfo session)
  {
    return (DynamoUser)(session.getObject(SessionInfoParams.NAMESPACE,SessionInfoParams.ATTR_USER));

  } // end getUser

  public DynamoUser getUser(Request request)
  {
    SessionInfoProvider prov = (SessionInfoProvider)(request.queryService(SessionInfoProvider.class));
    return this.getUser(prov.getSessionInfo());

  } // end getUser

  public DynamoUser lookupUser(Request req, String name) throws DatabaseException
  {
    if (StringUtils.isEmpty(name))
      return null;
    ObjectProvider op = (ObjectProvider)(req.queryService(ObjectProvider.class));
    UserManagement umgmt = (UserManagement)(op.getObject(Namespaces.DYNAMO_OBJECT_NAMESPACE,"users"));
    return umgmt.getUser(name);

  } // end lookupUser

  public DynamoUser lookupUser(Request req, int uid) throws DatabaseException
  {
    if (uid<=0)
      return null;
    ObjectProvider op = (ObjectProvider)(req.queryService(ObjectProvider.class));
    UserManagement umgmt = (UserManagement)(op.getObject(Namespaces.DYNAMO_OBJECT_NAMESPACE,"users"));
    return umgmt.getUser(uid);

  } // end lookupUser

  public int randomConfirmationNumber()
  {
    return m_rng.nextInt(CONFIRM_MAX - CONFIRM_MIN + 1) + CONFIRM_MIN;

  } // end randomConfirmationNumber

  public String randomPassword()
  {
    StringBuffer buf = new StringBuffer();
    int i;
    for (i=0; i<4; i++)   // 4 random syllables
      buf.append(SYLLABARY[m_rng.nextInt(SYLLABARY.length)]);
    for (i=0; i<3; i++)   // 3 random digits
      buf.append(DIGITS[m_rng.nextInt(DIGITS.length)]);
    return buf.toString();
    // total possible number of passwords = 92,236,816,000

  } // end randomPassword

  public String randomRecoveryAuth()
  {
    return String.valueOf(m_rng.nextInt(Integer.MAX_VALUE));

  } // end randomRecoveryAuth

  public String randomString(int len)
  {
    StringBuffer buf = new StringBuffer(len);
    for (int i=0; i<len; i++)
      buf.append(ALPHA_ARRAY[m_rng.nextInt(ALPHA_ARRAY.length)]);
    return buf.toString();

  } // end randomString

  public void setLocation(Request req, String location)
  {
    req.setObject(SessionInfoParams.REQ_NAMESPACE,SessionInfoParams.RATTR_LOCATION,location);

  } // end setLocation

  public void setDisplayLogin(Request req, boolean flag)
  {
    req.setObject(SessionInfoParams.REQ_NAMESPACE,SessionInfoParams.RATTR_DISPLAY_LOGIN,
		  Boolean.valueOf(flag));

  } // end setDisplayLogin

  public void setOnError(Request req, String on_error)
  {
    req.setObject(VeniceNamespaces.REQUEST_INFO_NAMESPACE,"on.error",on_error);

  } // end setOnError

  public void setOnErrorType(Request req, String on_error)
  {
    req.setObject(VeniceNamespaces.REQUEST_INFO_NAMESPACE,"on.error.type",on_error);

  } // end setOnErrorType

  public ErrorBox stdErrorBox(Request req, String title, String message)
  {
    String onerr = (String)(PropertyUtils.getPropertyNoErr(req,VeniceNamespaces.REQUEST_INFO_NAMESPACE,
							   "on.error"));
    String onerr_type = (String)(PropertyUtils.getPropertyNoErr(req,VeniceNamespaces.REQUEST_INFO_NAMESPACE,
								"on.error.type"));
    if (onerr!=null)
      return new ErrorBox(title,message,onerr_type,onerr);
    else
      return new ErrorBox(title,message);

  } // end stdErrorBox

} // end class LibraryVenice
