/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004 Bull S.A.
 * Contact: jonas-team@ow2.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 any 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(s): Florent BENOIT
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.db.base;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.jonas.jmx.JmxService;
import org.ow2.jonas.lib.service.AbsServiceImpl;
import org.ow2.jonas.lib.util.Log;
import org.ow2.jonas.service.ServiceException;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;

/**
 * Abstract database service to be implemented by implementation of Java
 * databases.
 * @author Florent Benoit
 */
public abstract class AbsDBServiceImpl extends AbsServiceImpl {

    /**
     * Property for the default database name.
     */
    private static final String DEFAULT_DATABASE_NAME = "db_jonas";

    /**
     * Logger used by this service.
     */
    private static Logger logger = Log.getLogger(Log.JONAS_DB_PREFIX);

    /**
     * Users' List.
     */
    private List<User> users;

    /**
     * DB port (null means default).
     */
    private String port = null;

    /**
     * Database name.
     */
    private String dbName = DEFAULT_DATABASE_NAME;

    /**
     * The{@link JmxService}
     */
    protected JmxService jmxService;

    /**
     * The {@link ObjectName} associate to the database MBean
     */
    protected ObjectName objectName;

    /**
     * port number used.
     */
    protected String portNumber = null;

    /**
     * Constructor initialization.
     */
    public AbsDBServiceImpl() {
        // Init user list
        this.users = new ArrayList<User>(); 
    }

    /**
     * Transform the pair user:pass into User instances.
     * @param users String of user/password (separated by a ":")
     */
    public void setUsers(final String users) {
        List<String> configuredUsers = convertToList(users);

        // Convert String user to real User.
        for (String user : configuredUsers) {
            if (logger.isLoggable(BasicLevel.DEBUG)) {
                logger.log(BasicLevel.DEBUG, "Adding user/password '" + user + "'.");
            }

            StringTokenizer st = new StringTokenizer(user, ":");
            String name = st.nextToken();
            String pass = "";
            if (st.hasMoreTokens()) {
                pass = st.nextToken();
            }
            this.users.add(new User(name, pass));
        }

    }

    /**
     * @param port Database port
     */
    public void setPort(final String port) {
        this.port = port;
    }

    /**
     * @param db Database name
     */
    public void setDbname(final String db) {
        this.dbName = db;
    }

    /**
     * Create a database with the specified arguments. Need to be implemented by
     * classes extending this one.
     * @param users user/password (separated by a ":")
     * @param databaseName name of the database
     * @param portNumber port number of the database
     */
    protected abstract void initServer(List<User> users, String databaseName, String portNumber) throws ServiceException;

    /**
     * Start the service.
     * @throws ServiceException if the startup failed.
     */
    @Override
    protected void doStart() throws ServiceException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }

        // Start the DB server
        initServer(users, dbName, port);

        //init the DB ObjectName
        initObjectName();

        //register the MBean
        registerMBean();
    }

    /**
     * Stop the service.
     * @throws ServiceException if the stop failed.
     */
    @Override
    protected void doStop() throws ServiceException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
    }

    /**
     * @return the logger.
     */
    public static Logger getLogger() {
        return logger;
    }

    /**
     * @param jmxService The {@link JmxService} to bind
     */
    public void bindJmxService(final JmxService jmxService) {
        this.jmxService = jmxService;
    }

    /**
     * @param jmxService The {@link JmxService} to unbind
     */
    public void unbindJmxService(final JmxService jmxService) {
        this.jmxService = null;
    }

    /**
     * Init DB ObjectName
     */
    private void initObjectName() {
        final String pattern = this.jmxService.getDomainName() + ":type=service,name=db";
        try {
            this.objectName = new ObjectName(pattern);
        } catch (MalformedObjectNameException e) {
            logger.log(BasicLevel.ERROR, "Cannot instanciate ObjectName with pattern '" + pattern, e);
        }        
    }

    /**
     * Register DB MBean
     */
    protected void registerMBean() {
        if (this.objectName != null) {
            try {
                this.jmxService.getJmxServer().registerMBean(this, objectName);
            } catch (InstanceAlreadyExistsException e) {
                logger.log(BasicLevel.ERROR, "Cannot register MBean with ObjectName " + objectName, e);
            } catch (MBeanRegistrationException e) {
                logger.log(BasicLevel.ERROR, "Cannot register MBean with ObjectName " + objectName, e);
            } catch (NotCompliantMBeanException e) {
                logger.log(BasicLevel.ERROR, "Cannot register MBean with ObjectName " + objectName, e);
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public String getPortNumber() {
        return this.portNumber;
    }

    /**
     * @return the name of the db
     */
    public String getDbName() {
        return this.dbName;       
    }

    /**
     * @return the list of pair of <username, password>
     */
    public String getDbUsers() {
        StringBuilder stringBuilder = new StringBuilder();
        for (User user: this.users) {
            stringBuilder.append(user.getUserName() + ":" + user.getPassword() + ",");                   
        }
        String users = stringBuilder.toString();
        if (users.length() > 0) {
            return users.substring(0, users.length() - 1);
        } else {
            return null;
        }
    }
}
