package org.richfaces.realworld.tree;

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

import javax.faces.model.SelectItem;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.richfaces.model.TreeNode;
import org.richfaces.realworld.domain.Album;
import org.richfaces.realworld.domain.Image;
import org.richfaces.realworld.domain.User;
import org.richfaces.realworld.service.IAlbumAction;
import org.richfaces.realworld.service.IImageAction;

@Name("treeRoot")
@Scope(ScopeType.PAGE)
public class TreeRootItem implements TreeNode {
	
	@In @Out
	private User user;
	
	private List<SelectItem> availableAlbums;
	
	private static final long serialVersionUID = -3530085227471752526L;
	
	private Map<Long, TreeAlbumItem> albums = null;

	public Map<Long, TreeAlbumItem> getAlbums() {
		if (this.albums==null) {
			initData();
		}
		return this.albums;
	}
	
	public void addAlbumToTree(TreeAlbumItem album) {
		addChild(album.getId(), album);
	}
	
	public void addChild(Object identifier, TreeNode child) {
		getAlbums().put((Long)identifier, (TreeAlbumItem)child);
		child.setParent(this);
	}

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

	public Iterator getChildren() {
		return getAlbums().entrySet().iterator();
	}

	public Object getData() {
		return this;
	}

	public TreeNode getParent() {
		return null;
	}

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

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

	public void setData(Object data) {
	}

	public void setParent(TreeNode parent) {
	}

	public String getType() {
		return "treeBean";
	}
	
	private void initData() {
		transformAlbumsToMap();
	}

	private void transformAlbumsToMap() {
		albums = new HashMap<Long, TreeAlbumItem>();
		availableAlbums = new ArrayList<SelectItem>();
		for(Album album:user.getChildAlbums()){
			TreeAlbumItem albumNode = new TreeAlbumItem(album.getId(), this, album);
			availableAlbums.add(new SelectItem(album.getName()));
			addAlbumToTree(albumNode);
		}
	}
	
	public void updateChild(Album album) {
		TreeAlbumItem albumItem = getAlbums().get(album.getId());
		albumItem.setAlbum(album);
	}	
	
	public SelectItem getSelectItemByName(String name) {
		for(SelectItem item : availableAlbums){
			if(item.getValue().toString().equals(name)){
				return item;
			}
		}
		return null;
	}
	
	public TreeAlbumItem getAlbumByName(String albumName) {
		for(Map.Entry<Long, TreeAlbumItem> entry : getAlbums().entrySet()){
			if(entry.getValue().getAlbum().getName().equals(albumName)){
				return entry.getValue();
			}
		}
		return null;
	}

	public List<SelectItem> getAvailableAlbums() {
		return availableAlbums;
	}
}
