001package net.filebot.cli;
002
003import java.util.Comparator;
004
005import groovy.lang.Closure;
006
007public class GroovyComparator implements Comparator<Object> {
008
009        private final Closure<?> closure;
010
011        public GroovyComparator(Closure<?> closure) {
012                this.closure = closure;
013        }
014
015        @Override
016        public int compare(Object o1, Object o2) {
017                Object result = closure.call(o1, o2);
018
019                if (result instanceof Number) {
020                        double d = ((Number) result).doubleValue();
021                        if (d > 0) {
022                                return 1;
023                        }
024                        if (d < 0) {
025                                return -1;
026                        }
027                        return 0;
028                }
029
030                throw new IllegalArgumentException("Invalid comparator: '" + result + "' is not a Number object");
031        }
032
033        @Override
034        public String toString() {
035                return "CLOSURE";
036        }
037
038        public static GroovyComparator wrap(Closure<?> closure) {
039                return new GroovyComparator(closure);
040        }
041
042}