/*
 * 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;
import org.w3c.dom.Node;

/**
 * @author Going Dot Com Inc.
 */
abstract class XbItem {

    protected Document doc;
    protected Connection conn;
    protected XbInterfaceDAO interfaceDAO;
    protected ArrayList<XbInterfaceObj> interfaceList;
    protected Element root;

    private ArrayList<String> nameSpaceList;

    protected XbItem(Connection conn, Document doc) {
        this.conn = conn;
        this.doc = doc;
        interfaceDAO = XbInterfaceDAO.getInstance(conn);
        nameSpaceList = new ArrayList<String>();
    }

    protected Element createElement(XbInterfaceObj obj) {
        // element作成
        StringBuffer str = new StringBuffer();
        str.append(obj.getNamespace());
        str.append(XbConstants.COLON_TYPE);
        str.append(obj.getItemName());
        // root属性名前空間設定
        if (!nameSpaceList.contains(obj.getNamespace())) {
            nameSpaceList.add(obj.getNamespace());
            this.root.setAttribute(XbConstants.NAMESPACE_XMLNS + obj.getNamespace(), obj.getNamespaceUrl());
        }
        return this.doc.createElement(str.toString());
    }

    protected void setAttribute(Element element, String footValue) {
        if (footValue != null) {
            String value = footValue.substring(1);
            element.setAttribute(XbConstants.ATTRIBUTE_ID, value);
        }
    }

    protected void appendChild(Element element, String value) {
        element.appendChild(this.doc.createTextNode(value));
    }

    protected void appendChild(Element element, Node node) {
        element.appendChild(node);
    }

    protected final void createItem(Element root) throws XbException {
        this.root = root;
        // item親要素取得
        interfaceList = interfaceDAO.select();
        if (interfaceList.size() > 0) {
            // item作成
            createItem();
        }
    }

    abstract protected void createItem() throws XbException;
}