/*
 Copyright 2004-2008 Paul R. Holser, Jr.  All rights reserved.
 Licensed under the Academic Free License version 3.0
 */

package joptsimple.internal;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

/**
 * @since 2.1
 * @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
 * @version $Id: Column.java,v 1.1 2008/04/01 21:46:46 pholser Exp $
 */
public class Column {
    static final Comparator BY_HEIGHT = new Comparator() {
        public int compare( Object first, Object second ) {
            int firstHeight = ( (Column) first ).height();
            int secondHeight = ( (Column) second ).height();

            if ( firstHeight < secondHeight )
                return -1;
            return firstHeight == secondHeight ? 0 : 1;
        }
    };

    private final String header;
    private final List data;
    private int width;
    private int height;

    Column( String header ) {
        this.header = header;
        data = new LinkedList();
        width = header.length();
        height = 0;
    }

    void addRow( Object row ) {
        String asString = String.valueOf( row );

        data.add( asString );
        width = Math.max( width, asString.length() );
        ++height;
    }

    void writeHeaderOn( StringBuffer buffer ) {
        buffer.append( header )
            .append( Strings.repeat( ' ', width - header.length() ) )
            .append( ' ' );
    }

    void writeSeparatorOn( StringBuffer buffer ) {
        buffer.append( Strings.repeat( '-', width ) )
            .append( ' ' );
    }

    void writeCellOn( int index, StringBuffer buffer ) {
        if ( index < data.size() ) {
            String item = (String) data.get( index );

            buffer.append( item )
                .append( Strings.repeat( ' ', width - item.length() ) )
                .append( ' ' );
        }
    }

    int height() {
        return height;
    }
}
