package com.quantum.view.bookmark;

import java.sql.SQLException;

import com.quantum.model.Bookmark;
import com.quantum.model.NotConnectedException;
import com.quantum.model.Schema;
import com.quantum.model.SchemaHolder;

/**
 * @author BC
 */
public class SchemaNode extends TreeNode implements SchemaHolder {

    private Schema schema;
    /**
     * @param parent
     */
    public SchemaNode(TreeNode parent, Schema schema) {
        super(parent);
        this.schema = schema;
    }

    /**
     * @see com.quantum.view.bookmark.TreeNode#getChildren()
     */
    public Object[] getChildren() {
        Bookmark bookmark = getBookmark();
        if (!bookmark.isConnected()) {
            return BookmarkListNode.EMPTY_ARRAY;
        } else {
            if (this.children.isEmpty()) {
                initializeChildren();
            }
        }
        return (TreeNode[]) this.children.toArray(new TreeNode[this.children.size()]);
    }

    protected void initializeChildren() {
        this.children.clear();
        Bookmark bookmark = getBookmark();
        try {
            String[] types = bookmark.getDatabase().getEntityTypes();
            for (int i = 0, length = (types == null) ? 0 : types.length;
                i < length;
                i++) {
                this.children.add(new GroupNode(this, this.schema, types[i]));
            }
        } catch (NotConnectedException e) {
        } catch (SQLException e) {
        }
    }

    /**
     * @see com.quantum.view.bookmark.TreeNode#hasChildren()
     */
    public boolean hasChildren() {
        return getBookmark().isConnected();
    }

    /**
     * @see com.quantum.view.bookmark.TreeNode#getName()
     */
    public String getName() {
        return this.schema.getDisplayName();
    }

    /**
     * @see com.quantum.view.bookmark.TreeNode#getImageName()
     */
    protected String getImageName() {
        return this.schema.isDefault() ? "user.gif" : "schema.gif";
    }

    /**
     * @see com.quantum.model.SchemaHolder#getSchema()
     */
    public Schema getSchema() {
        return this.schema;
    }
}