import java.awt.Rectangle;
import java.awt.Insets;
import javax.swing.JList;


public abstract class JListScrolling
{
    private JListScrolling()
    {
    }


    /** For completeness, and doesn't silently ignore bad arguments like
        the original.
    */
    public static void ensureIndexIsVisible(JList list, int index)
    {
        ensureIndicesAreVisible(list, index, index);
    }

    public static void ensureIndicesAreVisible(JList list, int first, int last)
    {
        checkIndices(list, first, last);

        Scrolling.scrollVertically(list, list.getCellBounds(first, last));
    }

    public static void ensureIndicesAreVisible(JList list, int first, int last, int bias)
    {
        checkIndices(list, first, last);

        Scrolling.scrollVertically(list, list.getCellBounds(first, last), bias);
    }


    public static void ensureIndexIsCentered(JList list, int index)
    {
        ensureIndicesAreCentered(list, index, index);
    }


    public static void ensureIndicesAreCentered(JList list, int first, int last)
    {
        checkIndices(list, first, last);

        Scrolling.centerVertically(list, list.getCellBounds(first, last), false);
    }
    
    public static boolean isIndexPartlyVisible(JList list, int index)
    {
        return areIndicesPartlyVisible(list, index, index);
    }


    public static boolean areIndicesPartlyVisible(JList list, int first, int last)
    {
        checkIndices(list, first, last);

        int listFirst = list.getFirstVisibleIndex();
        
        return listFirst != -1 && first >= listFirst && last <= list.getLastVisibleIndex();
    }

    public static boolean isIndexVisible(JList list, int index)
    {
        return areIndicesVisible(list, index, index);
    }

    public static boolean areIndicesVisible(JList list, int first, int last)
    {
        checkIndices(list, first, last);

        return Scrolling.isVerticallyVisible(list, list.getCellBounds(first, last));
    }
    

    private static void checkIndex(JList list, int index)
    {
        if (index < 0)
            throw new IndexOutOfBoundsException(index+" < 0");

        if (index >= list.getModel().getSize())
            throw new IndexOutOfBoundsException(index+" >= "+list.getModel().getSize());
    }


    private static void checkIndices(JList list, int first, int last)
    {
        if (first < 0)
            throw new IndexOutOfBoundsException(first+" < 0");

        if (first > last)
            throw new IndexOutOfBoundsException(first+" > "+last);

        if (last >= list.getModel().getSize())
            throw new IndexOutOfBoundsException(last+" >= "+list.getModel().getSize());
    }
}
