/**
 * 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 (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: ConfDeployerImpl.java 21830 2011-10-23 22:48:33Z cazauxj $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.addon.deploy.impl.deployer;

import org.codehaus.plexus.util.IOUtil;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.ow2.jonas.Version;
import org.ow2.jonas.addon.deploy.api.config.IAddonConfig;
import org.ow2.jonas.addon.deploy.api.deployable.IAddonDeployable;
import org.ow2.jonas.addon.deploy.api.util.IAddonLogEntry;
import org.ow2.jonas.addon.deploy.api.util.IAddonStructure;
import org.ow2.jonas.addon.deploy.impl.config.AddonConfigImpl;
import org.ow2.jonas.addon.deploy.impl.util.AddonDeployerLog;
import org.ow2.jonas.addon.deploy.impl.util.AddonUtil;
import org.ow2.jonas.lib.bootstrap.JProp;
import org.ow2.jonas.lib.util.ConfigurationConstants;
import org.ow2.jonas.properties.ServerProperties;
import org.ow2.util.archive.api.ArchiveException;
import org.ow2.util.archive.api.IArchive;
import org.ow2.util.ee.deploy.api.deployer.DeployerException;
import org.ow2.util.file.FileUtils;
import org.ow2.util.file.FileUtilsException;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;
import org.ow2.util.maven.plugin.mergeproperties.core.AggregateStrategy;
import org.ow2.util.maven.plugin.mergeproperties.core.MergeProperties;
import org.ow2.util.maven.plugin.mergeproperties.core.Preferences;
import org.ow2.util.maven.plugin.mergeproperties.core.Resource;
import org.ow2.util.maven.plugin.mergeproperties.core.Strategies;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import java.util.Dictionary;
import java.util.Hashtable;

/**
 * Represents a conf deployer
 */
public class ConfDeployerImpl {

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

    /**
     * The property name to register a new IAddonConfig component as an OSGi service
     */
    public final String SERVICE_REGISTRATION_ADDON_PROPERTY = "addon";

    /**
     * OSGi bundle context
     */
    private BundleContext bundleContext;

    /**
     * List of OSGi service registration
     */
    private List<ServiceRegistration> serviceRegistrations;

    /**
     * Default constructor
     * @param bundleContext OSGi bundle context
     */
    public ConfDeployerImpl(final BundleContext bundleContext) {
        this.bundleContext = bundleContext;
        this.serviceRegistrations = new ArrayList<ServiceRegistration>();
    }

    /**
     * deploy the configuration of an Addon
     * @param unpackedDeployable The unpacked addon to deploy
     * @param addonMetaData Metadata of the addon to unpacked
     * @param serverProperties ServerProperties
     * @param deployerLog The deployer log
     * @param addonResource Resource which contain the jonas.properties of the addon to deploy
     */
    public void deploy(final IAddonDeployable unpackedDeployable, final AddonMetaData addonMetaData,
                              final ServerProperties serverProperties, final AddonDeployerLog deployerLog,
                              final Resource addonResource) {

        //get configuration files
        String addonConfigurationPath = null;
        String addonDirectory = null;
        try {
            //get addon directory
            addonDirectory = unpackedDeployable.getArchive().getURL().getPath();
            addonConfigurationPath = addonDirectory + IAddonStructure.CONF_DIRECTORY;
        } catch (ArchiveException e) {
            logger.error("Cant get URL archive", e);
        }

        final String addonName = addonMetaData.getName();
        final String JOnASAddonDirectoryPath = AddonUtil.getAddonDirectoryPath(addonName);

        //create addons directory in $JONAS_BASE/conf if not exist
        File JOnASAddonDirectory = new File(JOnASAddonDirectoryPath);
        if (!JOnASAddonDirectory.exists()) {
            JOnASAddonDirectory.mkdirs();
        }

        //copy addon metadata
        File addonMetaDataFile = addonMetaData.getAddonMetaDataFile();
        try {
            FileUtils.copyFile(addonMetaDataFile.getAbsolutePath(), JOnASAddonDirectory + File.separator + addonMetaDataFile.getName());
        } catch (FileUtilsException e) {
            logger.error("Cannot copy file " + addonMetaDataFile.getAbsolutePath() + ".", e);
        }

        //copy others configuration files
        AddonUtil.copyFiles(addonConfigurationPath, JOnASAddonDirectoryPath);

        //copy the addon jonas.properties fragment into work/addons/addon/generated/jonas.properties
        updateGeneratedJonasPropertiesFragment(addonDirectory, addonMetaData);

        //register a new IAddonConfig component as an OSGi service
        try {
            register(JOnASAddonDirectoryPath, addonName);
        } catch (Exception e) {
            logger.error("Cannot register a new IAddonConfig component with " + JOnASAddonDirectoryPath + " directory", e);
        }

        //update JOnAS configuration
        generateJonasPropertiesFile(serverProperties, deployerLog, addonResource);
    }

    /**
     * Undeploy the configuration of an Addon
     * Retrieve the old JOnAS configuration
     * @param unpackedArchive The unpacked archive of the addon to deploy
     * @param addonMetaData Metadata of the addon to unpacked
     * @param serverProperties ServerProperties
     * @param addonDeployerLog The deployer log
     */
    public void undeploy(final IArchive unpackedArchive, final AddonMetaData addonMetaData,
                                final ServerProperties serverProperties, final AddonDeployerLog addonDeployerLog) {

        //delete the jonas.properties of the addon to undeploy
        String unpackedDeployablePath = null;
        try {
           unpackedDeployablePath = unpackedArchive.getURL().getPath();
        } catch (ArchiveException e) {
            logger.error("Cannot get the URL of the Archive to undeploy", e);
        }

        //the name of the addon to undeployed
        String addonName = addonMetaData.getName();

       //Map between the name of the addon to undeploy and the path to the deployable of the addon to undeploy
        Map<String, String> addonsToUndeploy = new HashMap<String, String>();
        addonsToUndeploy.put(addonName, unpackedDeployablePath);

        //unregister the IAddonConfig component with the given addon name
        unregister(addonName);

        //Retrieve JOnAS configuration
        retrieveJOnASConfiguration(serverProperties, addonDeployerLog, addonsToUndeploy, false);
    }

    /**
     * Retrieve JOnAS configuration
     * @param serverProperties ServerProperties
     * @param addonDeployerLog The Addon deployer log
     * @param addonsToUndeploy List of name of addon to undeploy
     * @param isJOnASStarting True if the server is starting. Otherwise, false.
     */
    public void retrieveJOnASConfiguration(final ServerProperties serverProperties, final AddonDeployerLog addonDeployerLog,
                                           final Map<String, String> addonsToUndeploy, final boolean isJOnASStarting) {
        //for each addon to undeploy, retrieve JOnAS configuration
        Iterator<String> it =  addonsToUndeploy.keySet().iterator();
        while (it.hasNext()) {
            String addonName = it.next();
            String unpackedDeployablePath = addonsToUndeploy.get(addonName);

            //delete the jonas.properties of the addon to undeploy
            deleteJonasPropertiesFragment(unpackedDeployablePath);

            //deletion of addon directory in $JONAS_BASE/conf
            String JOnASAddonDirectoryPath = AddonUtil.getAddonDirectoryPath(addonName);
            deleteFile(JOnASAddonDirectoryPath);
        }

        //if the server is starting, register an IAddonConfig service for each deployed addon
        if (isJOnASStarting) {
            Vector<IAddonLogEntry> logEntries = addonDeployerLog.getEntries();
            for (IAddonLogEntry logEntry: logEntries) {

                //register an IAddonConfig service for each deployed addon
                String addonName = logEntry.getName();
                String addonConfDirectory = AddonUtil.getAddonDirectoryPath(addonName);
                try {
                    register(addonConfDirectory, addonName);
                } catch (Exception e) {
                    logger.error("Cannot register a new IAddonConfig component with " + addonConfDirectory + " directory", e);
                }

                //When the user change the configuration for each addon in $JONAS_BASE/conf/addons/{addon.name}),
                //it's is copied into the ${work}/addons/${addon.name}/conf directory
                String addonMetaDataPath = AddonUtil.getAddonDirectoryPath(addonName) + File.separator + IAddonStructure.METADATA_FILENAME;

                File addonMetaDataFile = new File(addonMetaDataPath);
                if (addonMetaDataFile.exists()) {
                    String addonWorkDirectoryPath = logEntry.getCopy().getAbsolutePath();
                    AddonMetaData addonMetaData = AddonUtil.getAddonMetadata(addonMetaDataFile, addonWorkDirectoryPath);

                    //Update the generated jonas.properties fragment of an addon into the ${work}/addons/addon/generated directory
                    updateGeneratedJonasPropertiesFragment(addonWorkDirectoryPath, addonMetaData);

                    //copy $JONAS_BASE/conf/addons/{addon.name}/jonas-addon.xml into ${work}/addons/${addon.name}/META-INF directory
                    try {
                        FileUtils.copyFile(addonMetaDataPath, addonWorkDirectoryPath + File.separator + IAddonStructure.JONAS_ADDON_METADATA);
                    } catch (FileUtilsException e) {
                        logger.error("Cannot copy file " + addonMetaDataFile.getAbsolutePath() + ".", e);
                    }
                }

                //TODO: we need to copy only if the metadata file has been modified

            }


        }

        //update JOnAS configuration
        generateJonasPropertiesFile(serverProperties, addonDeployerLog);
    }

    /**
     * @param serverProperties ServerProperties
     * @return the Resource of the bootstrap
     */
    private Resource getBootstrapResource(final ServerProperties serverProperties) {

        //get jonas.properties bootstrap fragment
        File jonasPropertiesFile = new File(AddonUtil.JONAS_CONF_DIRECTORY, ConfigurationConstants.JONAS_PROPERTIES_PROP);

        FileInputStream jonasPropertiesInputStream = null;
        try {
            jonasPropertiesInputStream = new FileInputStream(jonasPropertiesFile);
        } catch (FileNotFoundException e) {
            logger.error("Cannot find jonas.properties file: " + serverProperties.getPropFileName() + " .", e);
        }

        Resource jonasPropertiesResource = new Resource(jonasPropertiesInputStream);
        jonasPropertiesResource.setName(jonasPropertiesFile.getAbsolutePath());

        return jonasPropertiesResource;
    }

    /**
     * Deletes a directory
     * @param directoryPath The directory to delete
     * @return true if all deletions were successful. Otherwise, false
     */
    public boolean deleteFile(final String directoryPath) {
        return FileUtils.delete(directoryPath);
    }

    /**
     * Generate jonas.properties file
     * @param serverProperties The server properties
     * @param addonDeployerLog The Addon deployer log
     */
    public void generateJonasPropertiesFile(final ServerProperties serverProperties,
                                                   final AddonDeployerLog addonDeployerLog) {

        //get jonas.properties bootstrap fragment
        Resource jonasPropertiesMasterResource = getBootstrapResource(serverProperties);

        //get jonas.properties fragment for each addon
        List<Resource> jonasPropertiesAddonResources = getJonasPropertiesAddonResources(addonDeployerLog);

        //generate jonas.properties file
        generateJonasPropertiesFile(serverProperties, jonasPropertiesMasterResource, jonasPropertiesAddonResources);
    }

    /**
     * Generate jonas.properties file
     * @param serverProperties The server properties
     * @param addonDeployerLog The Addon deployer log
     * @param resource A new resource wich is NOT describe in the addon deployer log
     */
    public void generateJonasPropertiesFile(final ServerProperties serverProperties,
                                                   final AddonDeployerLog addonDeployerLog,
                                                   final Resource resource) {
        //get jonas.properties bootstrap fragment
        Resource jonasPropertiesMasterResource = getBootstrapResource(serverProperties);

        //get jonas.properties fragment for each addon
        List<Resource> jonasPropertiesAddonResources = getJonasPropertiesAddonResources(addonDeployerLog);
        jonasPropertiesAddonResources.add(resource);

        //generate jonas.properties file
        generateJonasPropertiesFile(serverProperties, jonasPropertiesMasterResource, jonasPropertiesAddonResources);
    }

    /**
     * Generate jonas.properties file
     * @param serverProperties The server properties
     * @param jonasPropertiesMasterResource The jonas.properties bootstrap fragment
     * @param jonasPropertiesAddonResources jonas.properties fragment for each addon
     */
    private void generateJonasPropertiesFile(final ServerProperties serverProperties,
                                                    final Resource jonasPropertiesMasterResource,
                                                    final List<Resource> jonasPropertiesAddonResources) {
        //output file
        final String jonasPropertiesGenerated = serverProperties.getWorkDirectory() + File.separator + "conf-generated" +
        File.separator + "jonas.properties";

        //aggregate strategies
        AggregateStrategy aggregateStrategy1 = new AggregateStrategy();
        aggregateStrategy1.setKey("jonas.services");

        AggregateStrategy aggregateStrategies[] = new AggregateStrategy[1];
        aggregateStrategies[0] = aggregateStrategy1;

        List<String> fileOrderPreferences = new ArrayList<String>();
        fileOrderPreferences.add("jonas.*");
        fileOrderPreferences.add("jonas.service[.].*");

        //set preferences
        Preferences preferences = new Preferences();
        preferences.setFileOrderPreferences(fileOrderPreferences);

        //set strategies
        Strategies strategies = new Strategies();
        strategies.setAggregateStrategies(aggregateStrategies);

        //create a new MergeProperties objects with all resources, preferences and strategies
        MergeProperties mergeProperties = new MergeProperties();
        mergeProperties.setMasterResource(jonasPropertiesMasterResource);
        mergeProperties.setTemplateResources(jonasPropertiesAddonResources);
        mergeProperties.setOutputFile(jonasPropertiesGenerated);
        mergeProperties.setPreferences(preferences);
        mergeProperties.setStrategies(strategies);

        //generate jonas.properties file
        try {
            mergeProperties.execute();
        } catch (Exception e) {
            logger.error("Generation of " + jonasPropertiesGenerated + " failed.", e);
        }
    }


    /**
     * @param addonDirectory The directory where the addon is unpacked
     * @return the jonas.properties fragment of the addon
     */
    public String getJonasPropertiesFragment(final String addonDirectory) {
        return AddonUtil.getGeneratedWorkDirectory(addonDirectory) + File.separator + "jonas.properties";
    }

    /**
     * @param deployerLog The deployer log
     * @return jonas.properties fragment of each deployed addon
     */
    public List<Resource> getJonasPropertiesAddonResources(final AddonDeployerLog deployerLog) {
        List<Resource> jonasPropertiesAddonResources = new ArrayList<Resource>();

        if (deployerLog != null) {
            Vector<IAddonLogEntry> logEntries = deployerLog.getEntries();

            for (IAddonLogEntry logEntry: logEntries) {
                String jonasPropertiesFragment = getJonasPropertiesFragment(logEntry.getCopy().getAbsolutePath());
                InputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(jonasPropertiesFragment);
                } catch (FileNotFoundException e) {
                    logger.error("Cannot find the file " + jonasPropertiesFragment + ".", e);
                }
                Resource resource = new Resource(inputStream);
                resource.setName(jonasPropertiesFragment);
                jonasPropertiesAddonResources.add(resource);
            }
        }

        return jonasPropertiesAddonResources;
    }

    /**
     * Delete the jonas.properties of the addon to undeploy
     * @param unpackedDeployablePath
     */
    public void deleteJonasPropertiesFragment(final String unpackedDeployablePath) {
        deleteFile(getJonasPropertiesFragment(unpackedDeployablePath));
    }

    /**
     * @param addonName The name of an addon
     * @return the service registration which addon property value equals to the addon name
     */
    private ServiceRegistration getServiceRegistration(final String addonName) {
        for (ServiceRegistration serviceRegistration: this.serviceRegistrations) {
            if (serviceRegistration.getReference().getProperty(SERVICE_REGISTRATION_ADDON_PROPERTY).equals(addonName)) {
                return serviceRegistration;
            }
        }
        return null;
    }

    /**
     * Register a new IAddonConfig component
     * @param configurationDirectory The configuration directory of the addon
     * @param addonName The name of the addon
     */
    private void register(final String configurationDirectory, final String addonName) throws Exception {
        IAddonConfig addonConfig = new AddonConfigImpl(configurationDirectory);

        Dictionary<String, String> dictionary = new Hashtable<String, String>();
        dictionary.put(SERVICE_REGISTRATION_ADDON_PROPERTY, addonName);
        this.serviceRegistrations.add(this.bundleContext.registerService(IAddonConfig.class.getName(), addonConfig, dictionary));
    }

    /**
     * Unregister an IAddonConfig component associated to the given addon name
     * @param addonName The name of an addon
     */
    private void unregister(final String addonName) {
        getServiceRegistration(addonName).unregister();
    }



    /**
     * Update the generated jonas.properties fragment of an addon into the ${work}/addons/addon/generated directory
     * @param addonDirectory The directory where the addon is unpacked
     * @param addonMetaData  Metada of the addon
     */
    private void updateGeneratedJonasPropertiesFragment(final String addonDirectory, final AddonMetaData addonMetaData) {

        //copy the addon jonas.properties fragment into work/addons/addon/generated/jonas.properties
        final String jonasPropertiesFragmentPath = getJonasPropertiesFragment(addonDirectory);
        File jonasPropertiesFragment = new File(jonasPropertiesFragmentPath);
        if (!jonasPropertiesFragment.getParentFile().exists()) {
            jonasPropertiesFragment.getParentFile().mkdirs();
        }
        OutputStream output = null;
        try {
            output = new FileOutputStream(jonasPropertiesFragmentPath);
        } catch (FileNotFoundException e) {
            logger.error("Cannot create file "  + jonasPropertiesFragmentPath, e);
        }
        try {
            IOUtil.copy(addonMetaData.getResource().getInputStream(), output);
        } catch (IOException e) {
            logger.error("Cannot write jonas.properties fragment of into ", e);
        }
    }
}
