/**
 * 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.addon.deploy.impl.deployable;

import org.ow2.jonas.addon.deploy.impl.util.AddonUtil;

import java.util.Comparator;
import java.util.List;

/**
 * This class represents a comparator for AddonProvidesRequirements Class
 * @author Jeremy Cazaux
 */
public class AddonProvidesRequirementsComparator  implements Comparator<AddonProvidesRequirements> {

    /**
     * {@inheritDoc}
     */
    public int compare(AddonProvidesRequirements o1, AddonProvidesRequirements o2) {
        List<String> provides1 = o1.getProvides();
        List<String> provides2 = o2.getProvides();
        List<String> requirements1 = o1.getRequirements();
        List<String> requirements2 = o2.getRequirements();

        boolean doesO1RequireO2 = doesO1RequireO2(requirements1, provides2);
        boolean doesO2RequireO1 = doesO1RequireO2(requirements2, provides1);

        if (doesO1RequireO2 && !doesO2RequireO1) {
            return 1;
        } else if (doesO2RequireO1 && !doesO1RequireO2) {
            return -1;
        } else {
            return 0;
        }
    }

    /**
     * @param requirements List of requirements of addon 1
     * @param provides List of capabilities provides by addon 2
     * @return true if the first addon requires the second addon to be deployed
     */
    private boolean doesO1RequireO2(final List<String> requirements, final List<String> provides) {
        if (requirements != null) {
            for (String requirement: requirements) {
                if (AddonUtil.checkRequirement(requirement, provides)) {
                    return true;
                }
            }
        }
        return false;
    }
}
