/*
 * 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 XbUnitDivideDAO {
    // singleton作成
    private static XbUnitDivideDAO instance = null;
    private static Connection conn = null;

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

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

        return instance;
    }

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

            // メインリスト
            strb_sql.append("select ");
            strb_sql.append("ud.unit_id as unit_id ");
            strb_sql.append(", ud.divide_id as divide_id ");
            strb_sql.append(", dm.divide_type as divide_type ");
            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_divide ud ");
            strb_sql.append(", xb_divide_measure dm ");
            strb_sql.append(", xb_measure m ");
            strb_sql.append("where ");
            strb_sql.append("ud.unit_id = ? ");
            strb_sql.append("and ud.divide_id = dm.divide_id ");
            strb_sql.append("and dm.measure_id = m.measure_id ");
            // SQL設定
            stmt = conn.prepareStatement(strb_sql.toString());
            int index = 1;

            stmt.setString(index++, unitId);

            ResultSet rs = stmt.executeQuery();

            ArrayList<XbUnitDivideObj> relist = new ArrayList<XbUnitDivideObj>();
            while (rs.next()) {
                // サブリスト
                XbUnitDivideObj obj = new XbUnitDivideObj();
                obj.setUnitId(rs.getString("unit_id"));
                obj.setDivideId(rs.getString("divide_id"));
                obj.setDivideType(rs.getString("divide_type"));
                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());
        }
    }
}