/*
 * Joinery -- Data frames for Java
 * Copyright (c) 2014, 2015 IBM Corp.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.meteoinfo.dataframe.impl;

import org.meteoinfo.dataframe.DataFrame;

import java.util.*;

public class Sorting {

    public static <V> DataFrame sort(
            final DataFrame df, final Map<Integer, SortDirection> cols) {
        final Comparator<List<V>> comparator = new Comparator<List<V>>() {
            @Override
            @SuppressWarnings("unchecked")
            public int compare(final List<V> r1, final List<V> r2) {
                int result = 0;
                for (final Map.Entry<Integer, SortDirection> col : cols.entrySet()) {
                    final int c = col.getKey();
                    final V v2 = r2.get(c);
                    if (r1.get(c) instanceof Double && Double.isNaN((Double) r1.get(c))) {
                        if (v2 instanceof Double && Double.isNaN((Double) v2)) {
                            result = 0;
                        } else {
                            result = 1;
                        }
                    } else if (v2 instanceof Double && Double.isNaN((Double) v2)) {
                        result = -1;
                    } else {
                        final Comparable<V> v1 = Comparable.class.cast(r1.get(c));
                        try {
                            result = v1.compareTo(v2);
                        } catch (Exception e) {
                            result = 1;
                        }
                    }
                    result *= col.getValue() == SortDirection.DESCENDING ? -1 : 1;
                    if (result != 0) {
                        break;
                    }
                }
                return result;
            }
        };
        return sort(df, comparator);
    }

    public static <V> DataFrame sort(
            final DataFrame df, final Comparator<List<V>> comparator) {
        final DataFrame sorted = (DataFrame) df.clone();
        final Comparator<Integer> cmp = new Comparator<Integer>() {
            @Override
            public int compare(final Integer r1, final Integer r2) {
                return comparator.compare(df.row(r1), df.row(r2));
            }
        };

        final Integer[] rows = new Integer[df.length()];
        for (int r = 0; r < df.length(); r++) {
            rows[r] = r;
        }
        Arrays.sort(rows, cmp);

        final List<Object> labels = new ArrayList<>(df.getIndex().getData());
        int i = 0;
        for (final Integer r : rows) {
            final Object label = r < labels.size() ? labels.get(r) : r;
            sorted.getIndex().set(i, label);
            for (int c = 0; c < df.size(); c++) {
                sorted.setValue(i, c, df.getValue(r, c));
            }
            i += 1;
        }

        return sorted;
    }

    public static <V> DataFrame sortIndex(
            final DataFrame df, final SortDirection dir) {
        final Comparator<V> comparator = new Comparator<V>() {
            @Override
            @SuppressWarnings("unchecked")
            public int compare(final V v1, final V v2) {
                int result = 0;
                final Comparable<V> c1 = Comparable.class.cast(v1);
                try {
                    result = c1.compareTo(v2);
                } catch (Exception e) {
                    result = 1;
                }

                result *= dir == SortDirection.DESCENDING ? -1 : 1;
                return result;
            }
        };
        
        final DataFrame sorted = (DataFrame) df.clone();
        final Comparator<Integer> cmp = new Comparator<Integer>() {
            @Override
            public int compare(final Integer r1, final Integer r2) {
                return comparator.compare((V) (df.getIndex().get(r1)), (V) (df.getIndex().get(r2)));
            }
        };

        final Integer[] rows = new Integer[df.length()];
        for (int r = 0; r < df.length(); r++) {
            rows[r] = r;
        }
        Arrays.sort(rows, cmp);

        final List<Object> labels = new ArrayList<>(df.getIndex().getData());
        int i = 0;
        for (final Integer r : rows) {
            final Object label = r < labels.size() ? labels.get(r) : r;
            sorted.getIndex().set(i, label);
            for (int c = 0; c < df.size(); c++) {
                sorted.setValue(i, c, df.getValue(r, c));
            }
            i += 1;
        }

        return sorted;
    }
}
