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

import java.sql.*;
import java.util.*;
import org.apache.log4j.*;
import com.silverwrist.venice.core.*;
import com.silverwrist.venice.core.internals.*;
import com.silverwrist.venice.db.*;
import com.silverwrist.venice.except.*;
import com.silverwrist.venice.security.AuditRecord;
import com.silverwrist.venice.security.Role;

class AdminOperationsImpl implements AdminOperations
{
  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  private static Category logger = Category.getInstance(AdminOperationsImpl.class);

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

  private EnvUser env;                     // the execution environment

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

  AdminOperationsImpl(EnvUser env)
  {
    this.env = env;

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Implementations from interface AdminOperations
   *--------------------------------------------------------------------------------
   */

  public SecurityInfo getSecurityInfo()
  {
    return env.getEngine().getSelf().getSecurityInfo();

  } // end getSecurityInfo

  public List getAllowedRoleList()
  {
    if (env.testPermission(EnvUser.PERM_DESIGNATEPFY))
      return env.getRoleList("Global.UserLevelsPFY");
    else
      return env.getRoleList("Global.UserLevels");

  } // end getAllowedRoleList

  public List getAuditRecords(int offset, int count) throws DataException
  {
    Connection conn = null;
    List rc = null;

    try
    { // retrieve a connection from the data pool and get the audit records
      conn = env.getConnection();
      rc = AuditRecord.getAuditRecords(conn,-1,offset,count);

    } // end try
    catch (SQLException e)
    { // database error - this is a DataException
      logger.error("error loading audit records: " + e.getMessage(),e);
      throw new DataException("unable to load audit records: " + e.getMessage(),e);

    } // end catch
    finally
    { // make sure the connection is released before we go
      env.releaseConnection(conn);

    } // end finally

    return rc;

  } // end getAuditRecords

  public int getAuditRecordCount() throws DataException
  {
    Connection conn = null;
    int rc = -1;

    try
    { // retrieve a connection from the data pool and get the audit records
      conn = env.getConnection();
      rc = AuditRecord.getAuditRecordCount(conn,-1);

    } // end try
    catch (SQLException e)
    { // database error - this is a DataException
      logger.error("error loading audit record count: " + e.getMessage(),e);
      throw new DataException("unable to load audit record count: " + e.getMessage(),e);

    } // end catch
    finally
    { // make sure the connection is released before we go
      env.releaseConnection(conn);

    } // end finally

    return rc;

  } // end getAuditRecordCount

  public AdminUserContext getUserContext(int uid) throws DataException
  {
    return AdminUserContextImpl.getAdminUserContext(env,uid);

  } // end getUserContext

  public AdminUserContext getUserContext(String username) throws DataException
  {
    return AdminUserContextImpl.getAdminUserContext(env,username);

  } // end getUserContext

  public GlobalProperties getProperties()
  {
    return env.getEngine().getProperties();

  } // end getProperties

  public void setProperties(GlobalProperties props) throws DataException
  {
    env.getEngine().setProperties(props);

  } // end setProperties

  public AdminUserContext createNewAccount(String username, String password, String reminder,
					   boolean verify_email, boolean lockout, Role base_role,
					   String description) throws DataException, AccessError
  {
    if (logger.isDebugEnabled())
      logger.debug("createNewAccount(\"" + username + "\",<password>,<reminder>)...");

    if (base_role==null)
      base_role = env.getDefaultRole("Global.NewUser");

    // Create the user account.
    ReturnNewUser rnu = UserContextImpl.createAccount(env,env.getUser().userRemoteAddress(),username,
						      password,reminder,verify_email,lockout,0,base_role,
						      description);

    // Need to create a normal user context here for just a minute to autojoin the communities.
    UserContextImpl rc = new UserContextImpl(env);
    rc.loadNewUser("0.0.0.0",rnu.getUserID(),base_role.getLevel(),username,0,rnu.getCreationDate(),
		   rnu.getCreationDate());
    rc.autoJoinCommunities();

    // Now reload the user context and return it.
    return AdminUserContextImpl.getAdminUserContext(env,rnu.getUserID());

  } // end createNewAccount

} // end class AdminOperationsImpl
