/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007,2008 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: CmiServicePolicyStrategyManager.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.cmi.internal;

import java.io.FileNotFoundException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.cmi.controller.server.ServerClusterViewManager;
import org.ow2.cmi.lb.policy.IPolicy;
import org.ow2.cmi.lb.strategy.IStrategy;
import org.ow2.jonas.lib.util.Log;

/**
 * Manager for cmi policies and strategies. The Cmi service of JOnAS delegates
 * management of cmi policies and strategies to this class
 *
 * @author eyindanga
 */
public class CmiServicePolicyStrategyManager {
    /**
     * Logger.
     */
    private static Logger LOGGER = Log.getLogger("org.ow2.jonas.cmi");

    /**
     * server-side manager.
     */

    private ServerClusterViewManager serverClusterViewManager = null;

    /**
     * Stores the Ids of deployed bundles that export load balancing
     * policy/strategy.
     */
    private HashMap<String, BundleContent> deployedBundleId = new HashMap<String, BundleContent>();

    /**
     * Default constructor.
     */
    public CmiServicePolicyStrategyManager() {
    }

    /**
     * Constructor using fields.
     *
     * @param serverClusterViewManager
     *            the server-side manager to communicate with.
     */
    public CmiServicePolicyStrategyManager(
            final ServerClusterViewManager serverClusterViewManager) {
        this.serverClusterViewManager = serverClusterViewManager;
    }

    /**
     * Load the given archive.
     *
     * @param location
     *            of the bundle
     * @param policies
     *            the policies
     * @param strategies
     *            the strategies
     * @throws CmiServiceException
     *             any.
     */
    public void addPolicyStrategyBundle(final String location,
            final Class<? extends IPolicy<?>>[] policies,
            final Class<? extends IStrategy<?>>[] strategies)
            throws CmiServiceException {
        String bundleId = null;
        if (policies == null && strategies == null) {
            LOGGER.log(BasicLevel.DEBUG, "No strategies nor policies to be added");
            return;
        }
        Class<?>[] filteredPolicies = removeAbstractAndInterfaces(policies);
        Class<?>[] filteredStrategies = removeAbstractAndInterfaces(strategies);
        BundleContent policiesAndStrategies = new BundleContent(location,
                (Class<? extends IPolicy<?>>[]) filteredPolicies,
                (Class<? extends IStrategy<?>>[]) filteredStrategies);
        try {
            bundleId = CmiServiceHelper.sendBundle(serverClusterViewManager, policiesAndStrategies);
            if (deployedBundleId.containsKey(bundleId)) {
                deployedBundleId.remove(bundleId);
            }
            deployedBundleId.put(bundleId, policiesAndStrategies);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            LOGGER.log(BasicLevel.ERROR, "Unable to load archive located at '"
                    + policiesAndStrategies.getLocation() + "' because " + e);
            throw new CmiServiceException(e.getMessage());
        }

    }

    /**
     * Filter interfaces and abstract classes.
     *
     * @param classes
     *            the classes to filter.
     * @return filtered classes.
     */
    private Class<?>[] removeAbstractAndInterfaces(final Class<?>[] classes) {
        ArrayList<Class<?>> ret = new ArrayList<Class<?>>();
        if (classes != null) {
            for (Class<?> clz : classes) {
                if (!Modifier.isAbstract(clz.getModifiers())
                    && !Modifier.isInterface(clz.getModifiers())) {
                    ret.add(clz);
                }
            }
        }
        return ret.toArray(new Class[ret.size()]);
    }

    /**
     * Unload the given archive.
     *
     * @param location
     *            bundle location
     * @throws CmiServiceException any
     *
     */
    public void removePolicyStrategyBundle(final String location)
            throws CmiServiceException {
        try {
              String bundleId = null;
                bundleId = getBundleId(location);
                boolean isOwner = false;
                if (bundleId.contains(serverClusterViewManager.getUUID().toString())) {
                    /**
                     * Remove policies and strategies previously added from this bundle +
                     * Tell other servers to undeploy the bundle.
                     *
                     */
                    isOwner = true;
                }
                BundleContent bundleContent = deployedBundleId.get(bundleId);
                serverClusterViewManager.removeLoadBalancingArchive(bundleId,
                        bundleContent.getPolicyNames(), bundleContent.getStrategyNames(),
                        isOwner);
        } catch (Exception e) {
                throw new CmiServiceException(e.getMessage());
        }

    }

    /**
     * Gets Id for given bundle.
     *
     * @param location
     *            Bundle location
     * @return Id of the bundle.
     * @throws CmiServiceException
     *             if bundle is not deployed.
     */
    @SuppressWarnings("unchecked")
    private String getBundleId(final String location)
            throws CmiServiceException {
        // TODO Auto-generated method stub
        Iterator iter = deployedBundleId.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            BundleContent bundleContent = (BundleContent) entry.getValue();
            if (bundleContent.getLocation().equals(location)) {
                return key;
            }
        }
        throw new CmiServiceException(" Unable to find Id for bundle deployed at " + location);
    }

}
