/*
 * 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 XbEntity extends XbContext {

    private Document doc;

    private XbEntityDAO entityDAO;

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

        entityDAO = XbEntityDAO.getInstance(conn);
        etcDAO = XbSegmentDAO.getInstance(conn);
    }

    /**
     * Entity情報を作成する
     * @param entityId entityID
     * @return entityTag
     * @throws XbException
     */
    protected Element createEntity(String entityId, Element rootInstance) throws XbException {
        // entityTag
        Element entity = super.createElement(this.doc, XbConstants.TAG_ENTITY);
        // identifier情報取得
        ArrayList<XbEntityObj> identList = entityDAO.getEntity(entityId);

        for (int i = 0;i < identList.size();i ++) {
            XbEntityObj obj = identList.get(i);
            // identifierTag
            Element ident = super.createElement(this.doc, XbConstants.TAG_IDENTIFIER);
            super.setAttribute(ident, XbConstants.ATTRIBUTE_SCHEME, obj.getSchemaUri());
            super.appendChild(ident, this.doc, obj.getValue());
            // entityに設定
            super.appendChild(entity, ident);
        }

        // segment(root)情報取得
        ArrayList<XbEtcObj> segmentList = etcDAO.getEtc(entityId, "0");

        for (int i = 0;i < segmentList.size();i ++) {
            XbEtcObj obj = segmentList.get(i);
            // segmentTag
            Element segment = super.createElement(this.doc, XbConstants.TAG_SEGMENT);
            // root属性名前空間設定
            super.setAttribute(rootInstance, XbConstants.NAMESPACE_XMLNS + obj.getPrefix(), obj.getUri());
            // 再帰処理
            Element segItem = super.createEtc(this.doc, entityId, obj, obj.getPrefix());
            // segmentに設定
            super.appendChild(segment, segItem);
            // entityに設定
            super.appendChild(entity, segment);
        }

        return entity;
    }
}