/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2011 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 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
 *
 * --------------------------------------------------------------------------
 * $Id:RegistryServiceImpl.java 10372 2007-05-14 13:58:42Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.configadmin.internal;

import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.ow2.jonas.configadmin.internal.model.Configadmin;
import org.ow2.jonas.configadmin.internal.model.ConfigurationType;
import org.ow2.jonas.configadmin.internal.model.ObjectFactory;
import org.ow2.jonas.configadmin.internal.model.PropertyType;
import org.ow2.util.archive.api.ArchiveException;
import org.ow2.util.ee.deploy.api.deployable.IDeployable;
import org.ow2.util.ee.deploy.api.deployer.DeployerException;
import org.ow2.util.ee.deploy.api.deployer.IDeployer;
import org.ow2.util.ee.deploy.api.deployer.IDeployerManager;
import org.ow2.util.ee.deploy.api.deployer.UnsupportedDeployerException;
import org.ow2.util.file.FileUtils;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: guillaume
 * Date: 11/05/11
 * Time: 17:45
 * To change this template use File | Settings | File Templates.
 */
public class ConfigAdminDeployer implements IDeployer {

    /**
     * Logger.
     */
    private static final Log logger = LogFactory.getLog(ConfigAdminDeployer.class);

    private ConfigurationAdmin configAdmin;

    private JAXBContext context;

    private Map<String, List<Configuration>> store;

    public void validate() throws Exception {
        context = JAXBContext.newInstance(ObjectFactory.class);
        store = new Hashtable<String, List<Configuration>>();
    }

    /**
     * Bind method for the DeployerManager.
     * @param deployerManager the deployer manager.
     */
    public void registerDeployerManager(final IDeployerManager deployerManager) {
        deployerManager.register(this);
    }

    /**
     * Unbind method for the DeployerManager.
     * @param deployerManager the deployer manager.
     */
    public void unregisterDeployerManager(final IDeployerManager deployerManager) {
        deployerManager.unregister(this);
    }

    /**
     * Bind the reference to the ConfigurationAdmin service
     * @param admin CA service
     */
    public void bindConfigurationAdmin(ConfigurationAdmin admin) {
        this.configAdmin = admin;
    }


    public void deploy(IDeployable<?> untyped) throws DeployerException, UnsupportedDeployerException {
        ConfigAdminDeployable deployable = ConfigAdminDeployable.class.cast(untyped);
        URL url = getUrl(deployable);
        
        logger.info("Deploying Configurations for " + url);

        InputStream is = null;
        try {
            is = url.openStream();
            Source source = new StreamSource(is);

            Unmarshaller unmarshaller = context.createUnmarshaller();
            JAXBElement<Configadmin> element = unmarshaller.unmarshal(source, Configadmin.class);

            Configadmin ca = element.getValue();
            deployable.setAttachedData(ca);

            List<Configuration> configurations = new ArrayList<Configuration>();

            // Iterate over configurations and process them
            for (ConfigurationType configuration : ca.getConfigurations()) {
                Configuration c = createConfiguration(configuration);
                if (c != null) {
                    configurations.add(c);
                }
            }

            // Iterate over factory configurations and process them
            for (ConfigurationType configuration : ca.getFactoryConfigurations()) {
                Configuration c = createFactoryConfiguration(configuration);
                if (c != null) {
                    configurations.add(c);
                }
            }

            // Store the Configuration(s) object for undeployment
            store.put(url.toExternalForm(), configurations);

        } catch (IOException e) {
            throw new DeployerException("Cannot open " + deployable, e);
        } catch (JAXBException e) {
            throw new DeployerException("Cannot unmarshall " + deployable, e);
        } finally {
            FileUtils.close(is);
        }



    }

    /**
     * Create a factory typed Configuration from the JAXB model.
     * @param configuration JAXB model
     */
    private Configuration createFactoryConfiguration(final ConfigurationType configuration) {

        try {
            String servicePid = configuration.getPid();
            
            logger.debug("Create FactoryConfiguration for " + servicePid);

            // Create the factory configuration
            Configuration c = configAdmin.createFactoryConfiguration(servicePid, null);

            Properties properties = new Properties();
            for (PropertyType property : configuration.getProperties()) {
                properties.setProperty(property.getName(), property.getValue());
            }

            c.update(properties);

            logger.debug("Updated Factory" + c);

            return c;

        } catch (IOException e) {
            logger.warn("Cannot push Factory Configuration " + configuration.getPid(), e);
        }

        return null;

    }

    /**
     * Create a Configuration from the JAXB model.
     * @param configuration JAXB model
     */
    private Configuration createConfiguration(final ConfigurationType configuration) {

        try {
            String servicePid = configuration.getPid();

            logger.debug("Create Configuration for " + servicePid);

            // Find or create the configuration
            Configuration c = configAdmin.getConfiguration(servicePid, null);

            Dictionary dict = c.getProperties();
            if (dict == null) {
                dict = new Properties();
            }
            for (PropertyType property : configuration.getProperties()) {
                dict.put(property.getName(), property.getValue());
            }

            if (c.getBundleLocation() != null) {
                c.setBundleLocation(null);
            }

            c.update(dict);
            
            logger.debug("Updated " + c);

            return c;

        } catch (IOException e) {
            logger.warn("Cannot push Configuration " + configuration.getPid(), e);
        }

        return null;

    }

    private URL getUrl(IDeployable<?> deployable) throws DeployerException {
        URL url;
        try {
            url = deployable.getArchive().getURL();
        } catch (ArchiveException e) {
            throw new DeployerException("Cannot get URL of " + deployable, e);
        }
        return url;
    }

    public void undeploy(IDeployable<?> deployable) throws DeployerException {

        URL url = getUrl(deployable);

        logger.info("Undeploying Configurations for " + url);

        // Remove from store
        List<Configuration> configurations = store.remove(url.toExternalForm());

        // Remove the Configuration(s)
        for (Configuration configuration : configurations) {
            try {
                configuration.delete();
            } catch (Exception e) {
                logger.warn("Cannot delete Configuration " + configuration, e);
            }
        }
    }

    public boolean isDeployed(IDeployable<?> deployable) throws DeployerException {
        return store.containsKey(getUrl(deployable).toExternalForm());
    }

    public boolean supports(IDeployable<?> deployable) {
        return ConfigAdminDeployable.class.isAssignableFrom(deployable.getClass());
    }
}
