package com.dpd.general.services;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Category;

import net.sf.tapestry.ApplicationRuntimeException;


/**
 * This class is a generic implementation of <code>Service</code>.
 *
 * @author <a href="mailto:shomburg@hsofttec.com">Sven Homburg</a>
 * @version $Id$
 */
public abstract class BaseService implements Service
{
    /**
     * The name of this service.
     */
    public static final String SERVICE_NAME = "BaseService";

    /**
     * Initialization status of this class.
     */
    protected boolean isInitialized = false;

    /**
     * Configuration for this service.
     */
    protected Configuration configuration;

    /**
     * The name of this Service.
     */
    protected String name;

    /**
     * Implement this method with your own service initiailization
     * code.  Remember to call <code>setInit(true)</code> on proper
     * service initialization.
     *
     * @param conf the configuration for this service
     */
    public abstract void init(PropertiesConfiguration conf) throws ApplicationRuntimeException;

    /**
     * Returns an Initable to uninitialized state.
     *
     * Calls setInit(flase) to mark that we are no longer in initialized
     * state.
     */
    public void shutdown()
    {
        setInit(false);
    }

    /**
     * Returns either <code>Initialized</code> or
     * <code>Uninitialized</code>, depending upon
     * innitialization state.
     */
    public String getStatus() throws ApplicationRuntimeException
    {
        return (isInitialized() ? "Initialized" : "Uninitialized");
    }

    /**
     * Returns initialization status.
     *
     * @return True if the service is initialized.
     */
    public boolean isInitialized()
    {
        return isInitialized;
    }

    /**
     * Sets initailization status.
     *
     * @param value The new initialization status.
     */
    protected void setInit(boolean value)
    {
        this.isInitialized = value;
    }

    /**
     * ServiceBroker uses this method to pass a Service its name.
     *
     * @param name The name of this Service.
     */
    public void setName(String name)
    {
        this.name = name;
    }

    /**
     * Returns the name of this service.
     *
     * @return The name of this Service.
     */
    public String getName()
    {
        return name;
    }


    /**
     * Returns the configuration of this Service.
     *
     * @return The Configuration of this Service.
     */
    public Configuration getConfiguration()
    {
        return configuration;
    }

    /**
     * Returns the configuration of this Service.
     *
     * @param conf the configuration for this service
     */
    public void setConfiguration(Configuration conf)
    {
        configuration = conf.subset("services.properties." + getName());
    }
}
