/**
 * 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 22060 2012-01-29 12:43:56Z cazauxj $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.addon.deploy.impl.deployer;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
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.deployer.IAddonDeployerLog;
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.AddonUtil;
import org.ow2.util.archive.api.ArchiveException;
import org.ow2.util.archive.api.IArchive;
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 java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
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 service registration for IAddonConfig components
     */
    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
     */
    public void deploy(final IAddonDeployable unpackedDeployable, final AddonMetaData addonMetaData) {

        //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);

        //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);
        }
    }

    /**
     * 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 addonDeployerLog The deployer log
     */
    public void undeploy(final IArchive unpackedArchive, final AddonMetaData addonMetaData,
                         final IAddonDeployerLog<IAddonLogEntry> addonDeployerLog) {

        //get the path to the unpacked deployable
        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(addonDeployerLog, addonsToUndeploy, false);
    }

    /**
     * Retrieve JOnAS configuration
     * @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 IAddonDeployerLog<IAddonLogEntry> 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();

            //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();
                if (!addonsToUndeploy.containsKey(addonName)) {
                    String addonConfDirectory = AddonUtil.getAddonDirectoryPath(addonName);
                    try {
                        register(addonConfDirectory, addonName);
                    } catch (Exception e) {
                        logger.error("Cannot register a new IAddonConfig component with " + addonConfDirectory + " directory", e);
                    }
                }
            }
        }
    }

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

    /**
     * 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) {
        ServiceRegistration serviceRegistration = AddonUtil.getServiceRegistration(this.serviceRegistrations,
                SERVICE_REGISTRATION_ADDON_PROPERTY, addonName);
        if (serviceRegistration != null) {
            serviceRegistration.unregister();
            this.serviceRegistrations.remove(serviceRegistration);
        }
    }
}
