package org.jcon.df.util.security;

import org.jcon.util.GenLib;
import org.jcon.df.Database;
import org.jcon.df.request.Filter;
import org.jcon.df.work.DatabaseUtil;
import org.jcon.df.work.Row;

/**
 * Encapsulates the UserSys entity by handling all related
 * behavior and database access.
 *
 * @author Jack Harich
 */
public class UserEntity { 

//---------- Private Fields ------------------------------
private Database          database;
private DatabaseUtil      dbUtil; 
private static final String TABLE = "UserSys";

//---------- Properties ----------------------------------
public void setDatabase(Database database) {
    this.database = database;
    dbUtil = new DatabaseUtil(database);
}
//---------- Public Methods ------------------------------
/**
 * Returns the User with the userID and password, or returns
 * null if invalid.
 * <p>
 * If the UserSys table is empty a default row is added
 * using the userID and password, and the User is given
 * admin access. This handles the new database or no
 * defined users cases.
 */
public User createUser(String userID, String password) {
    // Validate userID and password
    Filter filter = new Filter();
    filter.addExpression("UserID", "=", userID);
    filter.addAnd();
    filter.addExpression("Password", "=", password);

    Row row = dbUtil.readRow(TABLE, filter);
    if (row != null) {
        // User is valid, so proceed 
        // Create User
        User user = new User();
        user.setMID(row.getLong(TABLE + ".MID"));
        user.setUserID(userID);         
        user.setFirstName(row.getString(TABLE + ".FirstName"));
        user.setMiddleInitial(row.getString(TABLE + ".MiddleInitial"));
        user.setLastName(row.getString(TABLE + ".LastName"));
        user.setAdmin(row.isTrue(TABLE + ".IsAdmin")); 
        user.setLogonTime(System.currentTimeMillis ());
        try {
            user.setUserProfileMID(row.getLong(TABLE + ".UserProfileMID"));
        } catch(Exception ex) {
            // Ignore, must be admin
        }
        // Create UserProfile for non-admin
        if (! user.isAdmin()) {
            UserProfile profile = UserProfile.createInstance(user, dbUtil);
            user.setUserProfile(profile);
        }
        // Done              
        return user; // <-----<<< 1st most common case
    }
    // row is null - Why?
    if (dbUtil.isEntityInDatabase("UserSys") == false) {
        // Table not in database
        GenLib.helpfulHint("The UserSys table is not in database " + database.getName() +".\n" +
            "Please add that and other tables and logoff.");
        User user = new User();
        user.setUserID(userID);
        user.setAdmin(true); // Can do anything
        return user; // <-----<<< Rare case

    } else if (dbUtil.countRows("UserSys", null) > 0) {
        // Table not empty so invalid user
        return null; // <-----<<< 2nd most common case
    }
    // Table empty
    row = createDefaultAdminRow(userID, password);
    if (row == null) return null; // Failure

    GenLib.helpfulHint("The UserSys table is empty.\n" +
        "A default Admin row has been added to the table.\n" +
        "Please edit appropriately and log off immediately.");
    User user = new User();
    user.setUserID(userID);
    user.setAdmin(true); // Can do anything
    return user; // <-----<<< 3rd most common case
}
//---------- Private Methods -----------------------------
// Returns null if failure
private Row createDefaultAdminRow(String userID, String password) {
    // Create row with all required fields
    Row row = new Row();
    row.setValue("UserSys.UserID",   userID);
    row.setValue("UserSys.Password", password);
    row.setValue("UserSys.IsAdmin", "1");

    row.setValue("UserSys.AdminCode", "AAA");
    row.setValue("UserSys.FirstName", "AAA");
    row.setValue("UserSys.LastName",  "AAA");
    row.setValue("UserSys.UserProfileMID", null);
    row.setValue("UserSys.LastLogon", "1/1/1990");

    // Add row to database
    boolean successful = dbUtil.addRow("UserSys", row);
    return (successful ? row : null);
}
//--- Std
private static void print(String text) {
    System.out.println("UserEntity" + text);
}
} // End class







