/*
 * Copyright (c) 2007, Going Dot Com Inc. All rights reserved.
 */

package jp.co.going.xbrl.instance;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import jp.co.going.xbrl.common.XbException;

/**
 * @author Going Dot Com Inc.
 */
class XbUnitMeasureDAO {
    // singleton作成
    private static XbUnitMeasureDAO instance = null;
    private static Connection conn = null;

    // コンストラクタ
    private XbUnitMeasureDAO() {
    }

    // インスタンス取得
    protected static synchronized XbUnitMeasureDAO getInstance(Connection connection) {
        // インスタンスを生成
        if (instance == null) {
            conn = connection;
            instance = new XbUnitMeasureDAO();
        }

        return instance;
    }

    protected ArrayList<XbUnitMeasureObj> getMeasure(String unitId) throws XbException {
        try {
            // ステートメントを作成
            PreparedStatement stmt;
            StringBuffer  strb_sql = new StringBuffer();

            // メインリスト
            strb_sql.append("select ");
            strb_sql.append("um.unit_id as unit_id ");
            strb_sql.append(", m.measure_id as measure_id ");
            strb_sql.append(", m.money_flag as money_flag ");
            strb_sql.append(", m.value as value ");
            strb_sql.append("from ");
            strb_sql.append("xb_unit_measure um ");
            strb_sql.append(", xb_measure m ");
            strb_sql.append("where ");
            strb_sql.append("um.unit_id = ? ");
            strb_sql.append("and um.measure_id = m.measure_id");
            // SQL設定
            stmt = conn.prepareStatement(strb_sql.toString());
            int index = 1;

            stmt.setString(index++, unitId);

            ResultSet rs = stmt.executeQuery();

            ArrayList<XbUnitMeasureObj> relist = new ArrayList<XbUnitMeasureObj>();
            while (rs.next()) {
                // サブリスト
                XbUnitMeasureObj obj = new XbUnitMeasureObj();
                obj.setUnitId(rs.getString("unit_id"));
                obj.setMeasureId(rs.getString("measure_id"));
                obj.setMoneyFlag(rs.getString("money_flag"));
                obj.setValue(rs.getString("value"));

                relist.add(obj);
            }
            // 結果セットをクローズ
            rs.close(); 
            // ステートメントをクローズ
            stmt.close(); 

            return relist;
        } catch (SQLException e) {
            throw new XbException(e, "SQLError : " + e.getMessage());
        }
    }
}