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

import de.sebse.fuplanner.tools.Regex;
import de.sebse.fuplanner.tools.SortedList;

public class SortedListModule extends SortedList<Modules.Module, String, String> {
    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 String getLatestSemester() {
        if (size() > 0)
            //noinspection ConstantConditions
            return this.get(0).semester;
        else
            return null;
    }

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

        String s1type = Regex.regex("^(S|WS) ", a);
        int s1year = Integer.parseInt(Regex.regex("^(S|WS) ([0-9]{2})", a, 2));
        String s2type = Regex.regex("^(S|WS) ", b);
        int s2year = Integer.parseInt(Regex.regex("^(S|WS) ([0-9]{2})", b, 2));

        if (s1year == s2year) {
            if (s1type.equals(s2type))
                return EQUAL;
            return s1type.equals("S") ? SMALLER : LARGER;
        }
        return s1year < s2year ? SMALLER : LARGER;
    }

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

    @Override
    public boolean hasFilter(Modules.Module o1, String filter) {
        return o1.semester.equals(filter);
    }
}
