package org.richfaces.realworld.tree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.richfaces.model.TreeNode;
import org.richfaces.realworld.domain.Album;
import org.richfaces.realworld.domain.Image;

public class TreeAlbumItem implements TreeNode {
	/**
	 * 
	 */
	private static final long serialVersionUID = 6514596192023597908L;
	private long id;
	private Map<Object, TreeNode> images = new LinkedHashMap<Object, TreeNode>();
	private Album album;
	TreeNode parent;

	public TreeAlbumItem(long id, TreeRootItem parent, Album album) {
		this.id = id;
		this.parent = parent;
		this.album = album;
		for(Image image:album.getImages()){
			TreeImageItem node = new TreeImageItem(image.getId(), this, image);
			addImage(node);
		}
	}
	
	public void addImage(TreeImageItem image) {
		addChild(image.getId(), image);
		image.setParent(this);
	}
	
	public void addChild(Object identifier, TreeNode child) {
		images.put(identifier, child);
	}

	public TreeNode getChild(Object id) {
		return (TreeNode) images.get(id);
	}

	public Iterator<Map.Entry<Object, TreeNode>> getChildren() {
		return images.entrySet().iterator();
	}
	
	public List<TreeNode> getImages() {
		List<TreeNode> imageCollection = new ArrayList<TreeNode>();
		imageCollection.addAll(images.values());
		return imageCollection;
	}

	public Object getData() {
		return this;
	}

	public TreeNode getParent() {
		return parent;
	}

	public boolean isLeaf() {
		return images.isEmpty();
	}

	public void removeChild(Object id) {
		images.remove(id);
	}

	public void setData(Object data) {
	}

	public void setParent(TreeNode parent) {
		this.parent = parent;
	}

	public long getId() {
		return id;
	}

	public Album getAlbum() {
		return album;
	}

	public void setAlbum(Album album) {
		this.album = album;
	}
	
	public String getType() {
		return "album";
	}
	
	public String toString(){
		return this.getAlbum().getName();
	}
}
