package de.sebse.fuplanner.services.kvv.types;

import androidx.annotation.Nullable;
import de.sebse.fuplanner.tools.SortedList;

public class SortedListModule extends SortedList<Modules.Module, String, Semester> {
    private static final int LARGER = 1;
    private static final int EQUAL = 0;
    private static final int SMALLER = -1;

    @Override
    public int compare(Modules.Module o1, Modules.Module o2) {
        int semester;
        try {
            semester = -compareSemester(o1.semester, o2.semester);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            semester = EQUAL;
        }
        if (semester != EQUAL)
            return semester;
        return o1.title.compareToIgnoreCase(o2.title);
    }

    @Override
    public void add(Modules.Module e) {
        super.add(e);
    }

    public Semester getLatestSemester() {
        if (size() > 0)
            //noinspection ConstantConditions
            return this.get(0).semester;
        else
            return null;
    }

    private static int compareSemester(@Nullable Semester a, @Nullable Semester b) throws NoSuchFieldException {
        if (a == null && b == null)
            return EQUAL;
        if (a == null)
            return SMALLER;
        if (b == null)
            return LARGER;


        if (a.getYear() == b.getYear()) {
            if (a.getType() == b.getType())
                return EQUAL;
            return a.getType() == Semester.SEM_SS ? SMALLER : LARGER;
        }
        return a.getYear() < b.getYear() ? SMALLER : LARGER;
    }

    @Override
    public boolean hasIdentifier(Modules.Module o1, String id) {
        return o1.getID().equals(id);
    }

    @Override
    public boolean hasFilter(Modules.Module o1, Semester filter) {
        return o1.semester != null && o1.semester.equals(filter);
    }
}
