/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 Bull S.A.
 * Contact: jonas-team@objectweb.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or 1any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Initial developer: Florent BENOIT
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.security.realm.principals;

import java.io.Serializable;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;

import org.objectweb.jonas.security.realm.lib.HashHelper;
import org.objectweb.jonas.security.realm.lib.HashPassword;
import org.objectweb.jonas.security.realm.lib.XML;

/**
 * This class define the User class which represent a user by its name,
 * password, etc.
 * @author Florent Benoit (initial developer)
 * @author Alexandre Thaveau (add DN for the certificates in method setName)
 * @author Marc-Antoine Bourgeot (add DN for the certificates in method setName)
 */
public class User implements Principal, Serializable, UserMBean {

    /**
     * Separator of the groups/roles
     */
    protected static final String SEPARATOR = ",";

    /**
     * Name of the user
     */
    private String name = null;

    /**
     * Password of the user
     */
    private String password = null;

    /**
     * Hash password of the user
     */
    private HashPassword hashPassword = null;

    /**
     * Groups
     */
    private Vector groups = new Vector();

    /**
     * Roles
     */
    private Vector roles = new Vector();

    /**
     * Combined roles
     */
    private ArrayList combinedRoles = new ArrayList();

    /**
     * Constructor
     */
    public User() {
    }

    /**
     * Constructor with a given login / password
     * @param name the given name
     * @param password the given password
     */
    public User(String name, String password) {
        setName(name);
        setPassword(password);
    }

    /**
     * Set the name of this user
     * @param name Name of the user
     */
    public void setName(String name) {
        if (name.startsWith("##DN##")) {
            //replace problematic caracters(for mbeans) by special caracters
            this.name = name.replace('=', '#').replace(',', '%').replace(' ', '$');
        } else {
            this.name = name;
        }
    }

    /**
     * Get the name of this user
     * @return the name of this user
     */
    public String getName() {
        return name;
    }

    /**
     * Get the password of this user
     * @return the password of this user
     */
    public String getPassword() {
        return password;
    }

    /**
     * Set the password of this user
     * @param password password of the user
     */
    public void setPassword(String password) {
        this.password = password;
        setHashPassword(HashHelper.getHashPassword(password));
    }

    /**
     * Set the hashed password of this user
     * @param hashPassword hashed password of this user
     */
    protected void setHashPassword(HashPassword hashPassword) {
        this.hashPassword = hashPassword;
    }

    /**
     * Set the hashed password of this user
     * @return hashPassword hashed password of this user
     */
    public HashPassword getHashPassword() {
        return hashPassword;
    }

    /**
     * Set the groups of the user
     * @param groups the comma separated list of the groups of the user
     */
    public void setGroups(String groups) {
        StringTokenizer st = new StringTokenizer(groups, SEPARATOR);
        String group = null;
        while (st.hasMoreTokens()) {
            group = st.nextToken().trim();
            addGroup(group);
        }
    }

    /**
     * Get the groups
     * @return the comma separated list of groups
     */
    public String getGroups() {
        String groupsList = "";
        Enumeration g = groups.elements();
        int nb = 0;
        String group = null;

        while (g.hasMoreElements()) {
            if (nb > 0) {
                groupsList += ", ";
            }
            group = (String) g.nextElement();
            groupsList += group;
        }
        return groupsList;

    }

    /**
     * Get the groups
     * @return the array of the groups
     */
    public String[] getArrayGroups() {
        return ((String[]) groups.toArray(new String[groups.size()]));
    }

    /**
     * Set the roles of the user
     * @param roles the comma separated list of the roles of the user
     */
    public void setRoles(String roles) {
        if (roles != null) {
            StringTokenizer st = new StringTokenizer(roles, SEPARATOR);
            String role = null;
            while (st.hasMoreTokens()) {
                role = st.nextToken().trim();
                addRole(role);
            }
        }
    }

    /**
     * Add the specified group to this user
     * @param group the group to add
     */
    public void addGroup(String group) {
        if (!groups.contains(group)) {
            this.groups.addElement(group);
        }
    }

    /**
     * Add a role to this user
     * @param role the given role
     */
    public void addRole(String role) {
        if (!roles.contains(role)) {
            this.roles.addElement(role);
        }
    }

    /**
     * Remove a group from this user
     * @param group the given group
     */
    public void removeGroup(String group) {
        if (groups.contains(group)) {
            this.groups.removeElement(group);
        }
    }

    /**
     * Remove a role from this user
     * @param role the given role
     */
    public void removeRole(String role) {
        if (roles.contains(role)) {
            this.roles.removeElement(role);
        }
    }

    /**
     * Get the roles
     * @return the array of the roles
     */
    public String getRoles() {
        String rolesList = "";
        Enumeration r = roles.elements();
        int nb = 0;
        String role = null;

        while (r.hasMoreElements()) {
            if (nb > 0) {
                rolesList += ", ";
            }
            role = (String) r.nextElement();
            rolesList += role;
        }
        return rolesList;
    }

    /**
     * Set the combined roles of this user
     * @param combinedRoles combined of the user
     */
    public void setCombinedRoles(ArrayList combinedRoles) {
        this.combinedRoles = combinedRoles;
    }

    /**
     * Get the combined roles of this user
     * @return the combined of the user
     */
    public ArrayList getCombinedRoles() {
        return combinedRoles;
    }

    /**
     * Get the roles
     * @return the array of the roles
     */
    public String[] getArrayRoles() {
        return ((String[]) roles.toArray(new String[roles.size()]));
    }

    /**
     * String representation of the user
     * @return the xml representation of the user
     */
    public String toXML() {
        StringBuffer xml = new StringBuffer("<user name=\"");
        xml.append(name);
        xml.append("\" password=\"");
        if (password != null) {
            xml.append(password);
        }
        xml.append("\"");
        XML.appendVectorToBuffer("groups=", xml, groups);
        XML.appendVectorToBuffer("roles=", xml, roles);
        xml.append(" />");
        return xml.toString();
    }

    /**
     * Use the XML representation of this object
     * @return the XML representation of this object
     */
    public String toString() {
        return this.toXML();
    }

}