package org.seasar.struts.config;

import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;

import org.codehaus.backport175.reader.Annotation;
import org.codehaus.backport175.reader.Annotations;
import org.seasar.struts.action.StrutsAction;
import org.seasar.struts.form.StrutsActionForm;


/**
 * @author Satoshi Kimura
 */
class ClassComparator implements Comparator {

    public int compare(Object o1, Object o2) {
        Class clazz1 = (Class) o1;
        Class clazz2 = (Class) o2;
        Annotation annotation1 = Annotations.getAnnotation(StrutsActionForm.class, clazz1);
        Annotation annotation2 = Annotations.getAnnotation(StrutsActionForm.class, clazz2);
        if (annotation1 == null) {
            annotation1 = Annotations.getAnnotation(StrutsAction.class, clazz1);
        }
        if (annotation2 == null) {
            annotation2 = Annotations.getAnnotation(StrutsAction.class, clazz2);
        }
        if (annotation1 != null && annotation2 != null) {
            return 0;
        } else if (annotation1 == null && annotation2 == null) {
            return 0;
        } else if (annotation1 != null) {
            return -1;
        } else {
            return 1;
        }
    }

    public static List sort(Collection collection) {
        Object[] objects = collection.toArray();
        Arrays.sort(objects, new ClassComparator());
        return Arrays.asList(objects);
    }
}
