//    Copyright 2011 Brad Block, Pawjaw, LLC. (brad@pawjaw.com)
//
//    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 com.pawjaw.utils;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;

public class SortedPairs implements Iterable<double[]>, Iterator<double[]> {
    private int p = 0, P;
    private double[][] pairs;
    
    public SortedPairs(int n) {
        pairs = new double[P = n][];
    }
    
    public void add(double[] element) {
        pairs[p++] = element;
    }
    
    public int size() {
        return P;
    }
    
    public SortedPairs sortDescending() {
        Arrays.sort(pairs, new Comparator() {
            public int compare(Object o1, Object o2) {
                if(o1 == null && o2 == null)
                    return 0;
                if(o1 == null)
                    return 1;
                if(o2 == null)
                    return -1;
                return ((double[])o1)[0] < ((double[])o2)[0] ? 1 : -1;
            }
        });
        p = 0;
        return this;
    }
    
    public SortedPairs sortAscending() {
        Arrays.sort(pairs, new Comparator() {
            public int compare(Object o1, Object o2) {
                if(o1 == null && o2 == null)
                    return 0;
                if(o1 == null)
                    return -1;
                if(o2 == null)
                    return 1;
                return ((double[])o1)[0] < ((double[])o2)[0] ? -1 : 1;
            }
        });
        p = 0;
        return this;
    }
    
    public double[] get(int p) {
        return pairs[p];
    }
    
    public double[] first() {
        return pairs[0];
    }
    
    public double[] last() {
        return pairs[P - 1];
    }
    
    public double[] next() {
        if(p >= P)
            return null;
        return pairs[p++];
    }

    public void reset() {
        p = 0;
    }

    public void increment(int pi) {
        p += pi;
    }

    public Iterator<double[]> iterator() {
        p = 0;
        return this;
    }
    
    public boolean hasNext() {
        return p < P;
    }
    
    public void remove() {
        throw new UnsupportedOperationException();
    }
}
