/*
 * 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 jp.co.going.xbrl.common.XbException;

/**
 * @author Going Dot Com Inc.
 */
class XbContextDAO{

    // singleton作成
    private static XbContextDAO instance = null;
    private static Connection conn = null;

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

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

        return instance;
    }

    protected XbContextObj getContext(String contextid) throws XbException {
        try {
            // ステートメントを作成
            PreparedStatement stmt;
            StringBuffer  strb_sql = new StringBuffer();

            // メインリスト
            strb_sql.append("select ");
            strb_sql.append("context_id ");
            strb_sql.append(", context_type ");
            strb_sql.append(", name ");
            strb_sql.append(", entity_id ");
            strb_sql.append(", period_start_date ");
            strb_sql.append(", period_end_date ");
            strb_sql.append(", item_precision ");
            strb_sql.append(", item_cwa ");
            strb_sql.append(", unit_flag ");
            strb_sql.append("from ");
            strb_sql.append("xb_context ");
            strb_sql.append("where ");
            strb_sql.append("context_id = ? ");
            // SQL設定
            stmt = conn.prepareStatement(strb_sql.toString());
            int index = 1;

            stmt.setString(index++, contextid);

            ResultSet rs = stmt.executeQuery();

            XbContextObj obj = new XbContextObj();
            if (rs.next()) {
                // サブリスト
                obj.setContextId(rs.getString("context_id"));
                obj.setContextType(rs.getString("context_type"));
                obj.setName(rs.getString("name"));
                obj.setEntityId(rs.getString("entity_id"));
                obj.setPeriodStartDate(rs.getString("period_start_date"));
                obj.setPeriodEndDate(rs.getString("period_end_date"));
                obj.setPrecision(rs.getString("item_precision"));
                obj.setCwa(rs.getString("item_cwa"));
                obj.setUnitFlag(rs.getString("unit_flag"));
            }
            // 結果セットをクローズ
            rs.close(); 
            // ステートメントをクローズ
            stmt.close(); 

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