/*
** Caramel - Core Java Toolbox
** Copyright (c) 2001, 2002, 2003 by Gerald Bauer
**
** This program is free software.
**
** You may redistribute it and/or modify it under the terms of the GNU
** General Public License as published by the Free Software Foundation.
** Version 2 of the license should be included with this distribution in
** the file LICENSE, as well as License.html. If the license is not
** included with this distribution, you may find a copy at the FSF web
** site at 'www.gnu.org' or 'www.fsf.org', or you may write to the
** Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/

package caramel.util;

import java.util.*;
import houston.*;

public class ColumnList
{
   static Logger T = Logger.getLogger( ColumnList.class );

   private List _list;

   public ColumnList( List list )
   {
      _list = list;
   }

   public List getList()
   {
      return _list;
      // return original list
   }

   public List[] getTableRows( int columns )
   {
      T.debug( "enter getList( " + columns + " )" );

      // reorders elements so that they
      //  can easily be traversed using velocity-foreach
      // example:
      // - before
      //   1 |  2 |  3
      //   4 |  5 |  6
      //   7 |  8 |  9
      //  10 | 11 | 12
      //  13 | 14
      //
      // after
      //   1 |  6 | 11
      //   2 |  7 | 12
      //   3 |  8 | 13
      //   4 |  9 | 14
      //   5 | 10
      // note: for every row one list is created

      Object data[] = _list.toArray();

      int size = data.length;
      int columnSize = size / columns;
      if( ( size % columns ) != 0 )
         // don't cut off last partially filled row
         columnSize += 1;

      T.debug( "size=" + size );
      T.debug( "columnSize=" + columnSize );

      // note: columnSize = number of rows

      List list[] = new List[columnSize];

      for( int row = 0; row < columnSize; row++ )
      {
         list[row] = new ArrayList();

         for( int col = 0; col < columns; col++ )
         {
            int index = ( col * columnSize ) + row;

            if( index >= size )
               continue;

            // T.debug( "row=" + row + ", col=" + col );
            // T.debug( "index=" + index );

            list[row].add( data[index] );
         }
      }

      T.debug( "leave getList()" );

      return list;
   }

}