/*
 * Copyright (c) 2009, Takeyuki Nagao
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the
 * following conditions are met:
 * 
 *  * Redistributions of source code must retain the above
 *    copyright notice, this list of conditions and the
 *    following disclaimer.
 *  * Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the
 *    following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *    
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 */

package jp.sourceforge.dvibrowser.dvicore.util.csv;
import java.util.ArrayList;
import java.util.logging.Logger;
public class CsvParser<K, V> {
  private static final Logger LOGGER = Logger.getLogger(CsvParser.class
      .getName());
  private final CsvCellCodec<K, V> codec;
  private CsvLineParser<K, V> lineParser;
  private final CsvData<K, V> csvData;
  
  public CsvParser(CsvCellCodec<K, V> codec, CsvData<K, V> csvData) {
    this.codec = codec;
    this.csvData = csvData;
    this.lineParser = new CsvLineParser<K, V>();
  }

  public void feed(String s)
  throws CsvException
  {
    LOGGER.fine("parsing line: " + s);
    for (char c : s.toCharArray()) {
      lineParser.feed(c);
    }
    lineParser.feed('\n');
  }
  
  public void close() throws CsvException
  {
    lineParser.close();

    String [] [] data = lineParser.getData();
    final int rows = data.length;
    
    if (rows > 0) {
      LOGGER.fine("ship out rows: " + rows);
      final int cols = data[0].length;

      ArrayList<K> keys = new ArrayList<K>();
      for (int j = 0; j < data[0].length; j++) {
        keys.add(codec.decodeKey(data[0][j]));
      }

      for (int i = 1; i < rows; i++) {
        csvData.beginLine();
        for (int j = 0; j < cols; j++) {
          K key = keys.get(j);
          V value = codec.decodeValue(key, data[i][j]);
          csvData.put(key, value);
          LOGGER.finer("key=" + key + " value=" + value);
        }
        csvData.endLine();
      }
    } else {
      LOGGER.fine("no data to ship out");
    }
  }
}
