/*
 * Copyright 2006-2011 the Seasar Foundation and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package org.seasar.codegen.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.seasar.framework.exception.IORuntimeException;

/**
 * Excel 関係のユーティリティ。
 * 
 * @author glad
 */
public class ExcelUtil {

    public static HSSFWorkbook createWorkbook(InputStream in) {
        try {
            return new HSSFWorkbook(in);
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
    }

    public static HSSFCell getCell(HSSFSheet sheet, int row, int col) {
        return getCell(sheet.getRow(row), col);
    }

    public static HSSFCell getCell(HSSFRow row, int col) {
        if (row == null) {
            return null;
        }
        return row.getCell((short) col);
    }

    public static String getString(HSSFSheet sheet, int row, int col) {
        return getString(getCell(sheet, row, col));
    }

    public static String getString(HSSFRow row, int col) {
        return getString(getCell(row, col));
    }

    public static String getString(HSSFCell cell) {
        if (cell == null) {
            return null;
        }
        int type = cell.getCellType();
        switch (type) {
        case HSSFCell.CELL_TYPE_BOOLEAN:
            return Boolean.toString(cell.getBooleanCellValue());
        case HSSFCell.CELL_TYPE_NUMERIC:
            double value = cell.getNumericCellValue();
            if (isInt(value)) {
                return Integer.toString((int) value);
            } else {
                return Double.toString(value);
            }

        case HSSFCell.CELL_TYPE_STRING:
            return trim(cell.getRichStringCellValue().getString());
        default:
            return "";
        }
    }

    /**
     * 整数かどうかを返します。
     * 
     * @param numericCellValue
     *            numericな値
     * @return 整数かどうか
     */
    protected static boolean isInt(final double numericCellValue) {
        return ((int) numericCellValue) == numericCellValue;
    }

    private static String trim(String s) {
        return (s == null) ? s : s.trim();
    }

}
