001/*
002 * (C) Copyright 2010 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Anahide Tchertchian
016 */
017package org.nuxeo.ecm.platform.forms.layout.api.impl;
018
019import java.util.Comparator;
020
021import org.nuxeo.ecm.platform.forms.layout.api.WidgetTypeConfiguration;
022import org.nuxeo.ecm.platform.forms.layout.api.WidgetTypeDefinition;
023
024/**
025 * Compares widget types on id or label.
026 *
027 * @author Anahide Tchertchian
028 * @since 5.4.2
029 */
030public class WidgetTypeDefinitionComparator implements Comparator<WidgetTypeDefinition> {
031
032    protected boolean compareLabels = false;
033
034    public WidgetTypeDefinitionComparator(boolean compareLabels) {
035        super();
036        this.compareLabels = compareLabels;
037    }
038
039    @Override
040    public int compare(WidgetTypeDefinition o1, WidgetTypeDefinition o2) {
041        if (o1 == null && o2 == null) {
042            return 0;
043        }
044        if (o1 == null) {
045            return -1;
046        }
047        if (o2 == null) {
048            return 1;
049        }
050        return getComparisonString(o1).compareTo(getComparisonString(o2));
051    }
052
053    protected String getComparisonString(WidgetTypeDefinition def) {
054        String res = def.getName();
055        if (compareLabels) {
056            WidgetTypeConfiguration conf = def.getConfiguration();
057            if (conf != null && conf.getTitle() != null) {
058                res = conf.getTitle();
059            }
060        }
061        return res;
062    }
063
064}