package info.bukova.isspst.ui.workgroups;

import java.util.Collection;
import java.util.LinkedList;

import info.bukova.isspst.Constants;
import info.bukova.isspst.data.JobMapping;
import info.bukova.isspst.data.Member;
import info.bukova.isspst.data.Workgroup;
import info.bukova.isspst.services.workgroups.WorkgroupService;

import org.zkoss.zul.DefaultTreeModel;
import org.zkoss.zul.TreeModel;
import org.zkoss.zul.TreeNode;

public class WorkgroupTreeFactory {
	
	private WorkgroupService workgroupService;
	
	public TreeModel<TreeNode<Member>> createTreeModel(Workgroup workgroup) {
		WorkgroupTreeNode root = new WorkgroupTreeNode(null, generateChildren(workgroup));
						
		return new DefaultTreeModel<Member>(root);
	}
	
	private Collection<WorkgroupTreeNode> generateChildren(Member member) {
		Collection<WorkgroupTreeNode> children = new LinkedList<WorkgroupTreeNode>();
		Workgroup workgroup = Workgroup.class.cast(member);
		
		workgroupService.loadMembers(workgroup);
		
		for (JobMapping jm : workgroup.getMembers()) {
			if (jm.getRole().getAuthority().equals(Constants.ROLE_USER) && jm.getMember().isPerson()) {
				children.add(new WorkgroupTreeNode(jm.getMember()));
			} else if (jm.getRole().getAuthority().equals(Constants.ROLE_USER)) {
				children.add(new WorkgroupTreeNode(jm.getMember(), generateChildren(jm.getMember())));
			}
		}
		
		return children;
	}

	public void setWorkgroupService(WorkgroupService workgroupService) {
		this.workgroupService = workgroupService;
	}

}
