001// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
002//
003// SPDX-License-Identifier: Apache-2.0
004
005package org.pgpainless.signature.consumer;
006
007import java.util.Comparator;
008
009import org.bouncycastle.openpgp.PGPSignature;
010
011/**
012 * Comparator which can be used to sort signatures with regard to their creation time.
013 */
014public class SignatureCreationDateComparator implements Comparator<PGPSignature> {
015
016    public static final Order DEFAULT_ORDER = Order.OLD_TO_NEW;
017
018    public enum Order {
019        /**
020         * Oldest signatures first.
021         */
022        OLD_TO_NEW,
023
024        /**
025         * Newest signatures first.
026         */
027        NEW_TO_OLD
028    }
029
030    private final Order order;
031
032    /**
033     * Create a new comparator which sorts signatures old to new.
034     */
035    public SignatureCreationDateComparator() {
036        this(DEFAULT_ORDER);
037    }
038
039    /**
040     * Create a new comparator which sorts signatures according to the passed ordering.
041     * @param order ordering
042     */
043    public SignatureCreationDateComparator(Order order) {
044        this.order = order;
045    }
046
047    @Override
048    public int compare(PGPSignature one, PGPSignature two) {
049        return order == Order.OLD_TO_NEW
050                ? one.getCreationTime().compareTo(two.getCreationTime())
051                : two.getCreationTime().compareTo(one.getCreationTime());
052    }
053}