/*
 * 作成日: 2009/05/09
 */
package asandatabasebrowser.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

/**
 * Excelでは、セルに改行やカンマなど区切り文字を含む場合は、ダブルクォーテーションで括られて
 * 出力されます。そのExcelで使われるCSV形式のファイルを読み込むためのクラスです。
 * @deprecated	開発中です。セル中にダブルクォートがある場合が抜けているはず。
 * 
 * @author a-san
 */
public class ExcelCsvFile {
	public static final int LINE_SEPARATOR = '\r';
	public static final int COLUMN_SEPARATOR = '\t';

	BufferedReader reader = null;
	ExcelCsvFile(File file, String charset)
			throws UnsupportedEncodingException, FileNotFoundException {
		reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
	}
	void close() throws IOException {
		reader.close();
	}
	String[] readLine()	throws IOException {
		if (reader == null) return null;
		if (! reader.ready()) return null;
		ArrayList result = new ArrayList();
		int ch = reader.read();
		while (true) {
			if (ch == -1) {
				reader.close();
				reader = null;
				break;
			}
			else if (ch == '\r' || ch == '\n') {
				if (ch == '\r') {
					reader.mark(1);
					ch = reader.read();
					if (ch != '\n') reader.reset();
				}
				break;
			}
			else if (ch == COLUMN_SEPARATOR) {
				result.add("");
				ch = reader.read();
			}
			else if (ch == '"') {
				String str = "";
				while (true) {
					ch = reader.read();
					if (ch == -1) return null;	// 不正
					if (ch == '"') break;
					str += (char) ch;
				}
				result.add(str);
				ch = reader.read();
				if (ch == '\t') ch = reader.read();
			}
			else {
				String str = "";
				while (true) {
					str += (char) ch;
					ch = reader.read();
					if (ch == '\t' || ch == '\r' || ch == '\n' || ch == -1) break;
				}
				result.add(str);
				if (ch == '\t') ch = reader.read();
			}
		}
		String[] r = new String[result.size()];
		for (int i=0; i<result.size(); i++) {
			r[i] = (String) result.get(i);
		}
		return r;
	}
	public static int insert(File file, String encoding) throws Exception {
		int count = 0;
		ExcelCsvFile cvs = new ExcelCsvFile(file, "UTF-8");
		while (true) {
			String[] line = cvs.readLine();
			if (line == null) break;
			for (int i=0; i<line.length; i++) {
				System.out.print("["+line[i]+"]");
			}
			System.out.println();
			count++;
		}
		return count;
	}
	public static void main(String[] args) throws Exception {
//		File file = new File("data/BIBLIO/Publishers.txt");
//		File file = new File("data/BIBLIO/Authors.txt");
		File file = new File("data/test.txt");
		ExcelCsvFile cvs = new ExcelCsvFile(file, "UTF-8");
		while (true) {
			String[] line = cvs.readLine();
			if (line == null) break;
			for (int i=0; i<line.length; i++) {
				System.out.print("["+line[i]+"]");
			}
			System.out.println();
		}
	}
}
