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

package jp.co.going.xbrl.instance;

import java.sql.Connection;
import java.util.ArrayList;

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.
 */
class XbUnit20 extends XbUnit {

    protected XbUnit20(Connection conn, Document doc) {
        super(conn, doc);
    }

    /**
     * Unit2.0情報を作成する
     * @param contextId contextId
     * @return unitTag
     * @throws XbException
     */
    protected Element createContextUnit(XbContextUnitObj unitObj, Element rootInstance) throws XbException {
        // unitTag
        Element unit = super.createElement(this.doc, XbConstants.TAG_UNIT);

        // measure情報取得
        ArrayList<XbUnitMeasureObj> measureList = XbUnitMeasureDAO.getInstance(super.conn).getMeasure(unitObj.getUnitId());
        // measure判定
        if (measureList.size() != 0) {  // measure
            XbUnitMeasureObj obj = measureList.get(0);
            // measureTag
            Element measure = super.createElement(super.doc, XbConstants.TAG_MEASURE);
            // node作成
            super.createMeasureTag(measure, obj.getMoneyFlag(), obj.getValue(), rootInstance, XbConstants.ISO4217_URI20);
            // unitに設定
            super.appendChild(unit, measure);
        } else {    // operator
            // divide情報取得
            ArrayList<XbUnitDivideObj> divideList = XbUnitDivideDAO.getInstance(super.conn).getDivide(unitObj.getUnitId());

            for (int i = 0;i < divideList.size(); i ++) {
                // operatorTag
                Element operator = super.createElement(super.doc, XbConstants.TAG_OPERATOR);
                XbUnitDivideObj obj = divideList.get(i);
                // 属性設定
                if (i == 0 && XbConstants.THREE_VALUE.equals(obj.getDivideType())) { // divide
                    super.setAttribute(unit, XbConstants.ATTRIBUTE_NAME, XbConstants.ATTRIBUTE_VALUE_DIVIDE);
                } else if (i == 0 && XbConstants.FOUR_VALUE.equals(obj.getDivideType())) { // multiply
                    super.setAttribute(unit, XbConstants.ATTRIBUTE_NAME, XbConstants.ATTRIBUTE_VALUE_MULTIPLY);
                }
                // node作成
                super.createMeasureTag(operator, obj.getMoneyFlag(), obj.getValue(), rootInstance, XbConstants.ISO4217_URI20);
                // unitに設定
                super.appendChild(unit, operator);
            }
        }
        return unit;
    }
}