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

package jp.co.going.xbrl.instance;

import java.sql.Connection;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * @author Going Dot Com Inc.
 */
abstract class XbUnit extends XbContext {

    protected Document doc;
    protected Connection conn;
    protected boolean iso4217Flg;

    private XbContextUnitDAO xbContextUnitDAO;

    protected XbUnit(Connection conn, Document doc) {
        this.doc = doc;
        this.conn = conn;

        xbContextUnitDAO = XbContextUnitDAO.getInstance(conn);
    }

    protected void createMeasureTag(Element element, String moneyFlg, String value, Element rootInstance, String uri) {
        // iso4217付与判定
        if (!iso4217Flg && XbConstants.ONE_VALUE.equals(moneyFlg)) {
            iso4217Flg = true;
            // root名前空間にiso4217_URI追加
            super.setAttribute(rootInstance, XbConstants.ISO4217_NAMESPACE, uri);
            // text設定
            super.appendChild(element, this.doc, XbConstants.ATTRIBUTE_ISO4217 + value);
        } else if (iso4217Flg && XbConstants.ONE_VALUE.equals(moneyFlg)) {
            // text設定
            super.appendChild(element, this.doc, XbConstants.ATTRIBUTE_ISO4217 + value);
        } else if (XbConstants.ZERO_VALUE.equals(moneyFlg)) {
            // text設定
            super.appendChild(element, this.doc, value);
        }
    }

    protected final Element createUnit(String contextId, Element rootInstance) throws XbException {
        Element unit = null;

        // unit情報取得
        XbContextUnitObj unitInfo = xbContextUnitDAO.getUnitInfo(contextId);

        // unitが存在したら処理を行う
        if (unitInfo != null) {
            // unit作成
            unit = this.createContextUnit(unitInfo, rootInstance);
        }

        return unit;
    }

    abstract protected Element createContextUnit(XbContextUnitObj unitInfo, Element rootInstance) throws XbException;
}