/*
 * 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.
 */
class XbContext20 extends XbContext {

    private Document doc;
    private XbEntity entity;
    private XbPeriod period;
    private XbUnit unit;
    private XbScenario scenario;

    protected XbContext20(Connection conn, Document doc) throws XbException {
        this.doc = doc;

        entity = new XbEntity(conn, doc);
        period = new XbPeriod(doc);
        unit = new XbUnit20(conn, doc);
        scenario = new XbScenario(conn, doc);
    }

    /**
     * コンテキストタグを作成する
     * @param obj コンテキスト情報
     * @param rootElement rootタグ
     * @throws XbException
     */
    protected Element createContext(XbContextObj obj, Element rootElement) throws XbException {

        Element context = null;
        // contextタグ作成(nonNumeric/numeric)
        if (XbConstants.ATTRIBUTE_NO_NUMERIC.equals(obj.getContextType())) {
            context = super.createElement(this.doc, XbConstants.TAG_NONNUMERICCONTEXT);
        } else {
            context = super.createElement(this.doc, XbConstants.TAG_NUMERICCONTEXT);
            // precision属性追加
            super.setAttribute(context, XbConstants.ATTRIBUTE_PRECISION, obj.getPrecision());
            // cwa属性追加
            if (XbConstants.ONE_VALUE.equals(obj.getCwa())) {
                super.setAttribute(context, XbConstants.ATTRIBUTE_CWA, XbConstants.ATTRIBUTE_VALUE_TRUE);
            } else {
                super.setAttribute(context, XbConstants.ATTRIBUTE_CWA, XbConstants.ATTRIBUTE_VALUE_FALSE);
            }
        }
        // id属性追加
        super.setAttribute(context, XbConstants.ATTRIBUTE_ID, obj.getName());

        // entityタグ作成
        Element entityTag = entity.createEntity(obj.getEntityId(), rootElement);
        // periodタグ作成
        Element periodTag = period.createPeriod(obj.getPeriodStartDate(), obj.getPeriodEndDate());
        // unitタグ作成
        Element unitTag = unit.createUnit(obj.getContextId(), rootElement);
        // scenarioタグ作成
        Element scenarioTag = scenario.createScenario(obj.getContextId(), rootElement);

        // contextタグに追加
        super.appendChild(context, entityTag); // entity
        super.appendChild(context, periodTag); // period
        // unit_flag
        if (XbConstants.ATTRIBUTE_NUMERIC.equals(obj.getContextType()) || 
                (XbConstants.ATTRIBUTE_NO_NUMERIC.equals(obj.getContextType()) && 
                        XbConstants.ONE_VALUE.equals(obj.getUnitFlag()))) {
            super.appendChild(context, unitTag); // unit
        }

        super.appendChild(context, scenarioTag); // scenario

        return context;
    }
}