/*
 * Scone - The Web Enhancement Framework
 * Copyright (C) 2009 Harald Weinreich, Volkert Buchmann, Frank Wollenweber, Torsten Haß
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
 package scone.netobjects;


import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Vector;


/**
 * This Class is used to access User objects and cache them in a hashtable.
 *
 * @author Harald Weinreich
 * @author Volkert Buchmann
 */

public class UserCache implements TableRecordCacheInterface {
    protected static CacheTable cache;

    public static Object lock = new Object();
   
    public static void init(int timeTillCleanUp, int gcType) {
        cache = new CacheTable("Users", 2, timeTillCleanUp, gcType);
        lock = new Object();
    }
   
    // return user by id
    public static User getById(String id) {
        User user = null;

        if (Long.parseLong(id) > 0) {
            synchronized (lock) {
                user = (User) cache.get(0, id);
                if (user == null) {
                    user = new User(Long.parseLong(id));      // New user object is created in DB isuser is not known
                    cache.put(user);        // the username is, however, empty!
                }
            }
        }
        return user;
    }

    // return user by id
    public static User checkById(String id) {
        User user = null;

        synchronized (lock) {
            user = (User) cache.get(0, id);
            if (user == null) {
                user = new User(Long.parseLong(id), false);      // check only, do not create if not in db!
                if (user.hasRecordInDB || !User.dbTable.useDb) {
                    cache.put(user);
                }     // USer found in db or DB not in use...
                else {  // User not found in DB
                    return null;
                }
            }
        }
        return user;
    }

    // return user by name
    public static User get(String name) {
        User user = null;

        synchronized (lock) {
            user = (User) cache.get(1, name);
            if (user == null) {      // not in cache: Create get from DB or create new.
                user = new User(name);
                cache.put(user);
            }
        }
        return user;
    }

    /**
     * Check if the user exists in Cache or DB AND if password is right.
     * Return user object if user and password found, otherwise return null.
     */
    // check if user with this password exists...
    public static User check(String name, String password) {
        User user = null;

        synchronized (lock) {
            user = (User) cache.get(1, name);   // Gibt es den user im Chache?
            if (user == null)    // nicht
            {
                user = new User(name, false);  // checkonly if in DB!
                if (user.hasRecordInDB) // Gibt es den user un der DB?
                {
                    cache.put(user);
                } else {
                    return null;     // User onknown!
                }
            } 
            // user found in cache or db:
            if (user.getUserPass().equals(password))  // check password.
            {
                return user;
            } else {
                return null;  // wrong password...     
            }
        }
    }

    // Return all Users
    /**
     * This method returns a Vector of users to a given query string
     * @param sqlClause The where clause for the query string.
     */
    public static Vector getUsers(String sqlClause) {
        Connection con = User.dbTable.getConnection();
        Vector users = new Vector();
        int i = 0;

        synchronized (lock) {
            ResultSet results = User.dbTable.queryDb(con, User.dbTable.getTableName(), sqlClause);

            // eval all records returned...
            while (results != null) {
                User user = new User(results);  // Create new use object
                String id = user.getUserId();

                if (id.length() > 0 && !id.equals("-1") && !id.equals("NULL")) // another set read from DB      
                {              
                    // System.out.println(results.getString("userId") + "  " +results.getString("userName"));
                    if (cache.get(0, id) == null) {   // user not known in cache...
                        cache.put(user);
                    }
                    users.add(user);
                } else {  // End of results reached!
                    return users;
                }
            }
        }
        return users;
    }

    /**
     * save cache to DB
     */   
    public static void clean() {
        cache.clean();
    }
   
}
