package components.matchtable;

import objects.SoccerMatchAnalysis;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import java.io.Serializable;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class SortableSoccerMatchAnalysisDataProvider extends SortableDataProvider<SoccerMatchAnalysis, String> {

    class SortableDataProviderComparator implements Comparator<SoccerMatchAnalysis>, Serializable {

        @Override
        public int compare(SoccerMatchAnalysis o1, SoccerMatchAnalysis o2) {
            PropertyModel<Comparable> model1 = new PropertyModel<>(o1, getSort().getProperty());
            PropertyModel<Comparable> model2 = new PropertyModel<>(o2, getSort().getProperty());

            int result = model1.getObject().compareTo(model2.getObject());
            if (!getSort().isAscending()) {
                result = -result;
            }
            return result;
        }
    }
    List<SoccerMatchAnalysis> matches;
    private SortableDataProviderComparator comparator = new SortableDataProviderComparator();

    public SortableSoccerMatchAnalysisDataProvider(List<SoccerMatchAnalysis> matches) {
        this.matches = matches;
        setSort("calculatedPercentages.drawPercentage", SortOrder.DESCENDING);
    }

    @Override
    public Iterator<SoccerMatchAnalysis> iterator(long first, long count) {

        matches.sort(comparator);

        return matches.subList((int)first, (int)(first + count)).iterator();
    }

    @Override
    public long size() {
        return matches.size();
    }

    @Override
    public IModel<SoccerMatchAnalysis> model(SoccerMatchAnalysis object) {
        return Model.of(object);
    }

}
