package jp.bne.deno.ordermaid.common;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
 * Excel管理用の基底クラス
 * 
 * @author hasegawt
 * 
 */
public abstract class ExcelReportBuilder {

	/**
	 * 操作対象のワークブック.
	 */
	private WritableWorkbook workbook;

	/**
	 * 現在編集中のシート.
	 */
	protected WritableSheet sheet;

	/**
	 * 初期化
	 * 
	 * @param file
	 */
	public void initialize(File file, InputStream stream) throws IOException {
		WorkbookSettings settings = new WorkbookSettings();
		settings.setGCDisabled(true);
		settings.setLocale(new Locale("ja", "JP"));
		settings.setEncoding("Windows-31J");
		try {
			workbook = Workbook.createWorkbook(file, Workbook
					.getWorkbook(stream), settings);
		} catch (BiffException e) {
			throw new IOException(e);
		}
		sheet = workbook.getSheet(0);
	}

	/**
	 * 終了処理
	 */
	public void writeOut() {
		if (workbook == null) {
			return;
		}
		try {
			workbook.write();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			workbook.close();
		} catch (WriteException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 編集するシート名を設定する。
	 * 
	 * @param sheetName
	 */
	public void setSheet(String sheetName) {
		sheet = workbook.getSheet(sheetName);
	}

}
