/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the
 * License at
 * http://www.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2015 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */
package com.icesoft.faces.facelets.component.treetable;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


public class TreeTable implements Serializable {

    private TreeTableNode rootNode;
    private ITreeTableListener listener;
    private List linearizedTree;
    private long updateTimestamp;

    public void setRootNode(TreeTableNode rootNode) {
        this.rootNode = rootNode;
        rebuildList();
    }

    public TreeTable() {
    }

    public TreeTable(ITreeTableListener listener) {
        this.listener = listener;
    }

    /**
     * @return The rendered state of the tree table
     *         (only shows the currently displayed treeTable nodes)
     */
    public List getLinearizedTree() {
        return linearizedTree;
    }

    /**
     * Event for rebuilding the tree table list after
     * the treeModel has been changed. This event should
     * be raised whenever the treeModel changes.
     * (must be called as an event to force Seam to uncache
     * the previous list value)
     */
    public void rebuildList() {
        if (linearizedTree == null)
            linearizedTree = new ArrayList();
        else
            linearizedTree.clear();
        linearizedTree.add(rootNode);
        if (rootNode.userObject.isExpanded())
            addChildrenToList(rootNode);
    }

    private void addChildrenToList(TreeTableNode node) {
        for (Object o : node.getChildren()) {
            TreeTableNode child = (TreeTableNode) o;
            linearizedTree.add(child);
            if (child.userObject.isExpanded()) {
                addChildrenToList(child);
            }
        }
    }

    public ITreeTableListener getListener() {
        return listener;
    }

	public long getUpdateTimestamp() {
		return updateTimestamp;
	}

	public void updateTimestamp() {
		this.updateTimestamp = System.currentTimeMillis();
	}


}

