/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * 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 (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.ssh.internal;

import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.ow2.jonas.jmx.JmxService;
import org.ow2.jonas.lib.service.AbsServiceImpl;
import org.ow2.jonas.service.ServiceException;
import org.ow2.jonas.ssh.SshService;
import org.ow2.shelbie.commands.ssh.server.Constants;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import java.io.IOException;
import java.util.Properties;

/**
 * @author Loris Bouzonnet
 */
public class SshServiceImpl extends AbsServiceImpl implements SshService, SshServiceImplMBean {
    
    private int port;

    private ConfigurationAdmin configurationAdmin;

    private Configuration configuration;

    /**
     * The {@link ObjectName} associated to this MBean
     */
    private ObjectName objectName;

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

    /**
     * The logger 
     */
    private static Log logger = LogFactory.getLog(SshServiceImpl.class);

    /**
     * {@inheritDoc}
     */
    protected void doStart() throws ServiceException {
        try {
            configuration = configurationAdmin.createFactoryConfiguration(
                    Constants.SSHD_COMPONENT_NAME, null);
        } catch (IOException e) {
            throw new ServiceException("Unable to create a new configuration for the SSH server", e);
        }
        Properties properties = new Properties();
        properties.setProperty(Constants.SSHD_PORT, String.valueOf(port));
        try {
            configuration.update(properties);
        } catch (IOException e) {
            throw new ServiceException("Unable to update the configuration of the SSH server", e);
        }

        //build the ObjectName and register the MBean
        final String pattern = this.jmxService.getDomainName() + ":type=service,name=ssh";
        try {
            this.objectName = new ObjectName(pattern);
        } catch (MalformedObjectNameException e) {
            logger.error("Cannot instantiate ObjectName with pattern equals to '" + pattern + "'", e);
        }
        try {
            this.jmxService.getJmxServer().registerMBean(this, this.objectName);
        } catch (InstanceAlreadyExistsException e) {
            logger.error("Cannot register MBean with ObjectName " + objectName, e);
        } catch (MBeanRegistrationException e) {
            logger.error("Cannot register MBean with ObjectName " + objectName, e);
        } catch (NotCompliantMBeanException e) {
            logger.error("Cannot register MBean with ObjectName " + objectName, e);
        }

    }

    /**
     * {@inheritDoc}
     */
    protected void doStop() throws ServiceException {
        if (configuration != null) {
            try {
                configuration.delete();
            } catch (IOException e) {
                throw new ServiceException("Unable to delete the configuration of the SSH server", e);
            }
        }

        //unregister the MBean
        this.jmxService.unregisterMBean(this.objectName);
    }

    public ConfigurationAdmin getConfigurationAdmin() {
        return configurationAdmin;
    }

    public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) {
        this.configurationAdmin = configurationAdmin;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * @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;
    }
}
