package info.bukova.isspst.ui.workgroups;

import java.util.List;

import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.TreeModel;
import org.zkoss.zul.TreeNode;

import info.bukova.isspst.data.Member;
import info.bukova.isspst.data.Role;
import info.bukova.isspst.data.Workgroup;
import info.bukova.isspst.filters.WorkgroupFilter;
import info.bukova.isspst.services.users.RoleService;
import info.bukova.isspst.services.workgroups.WorkgroupService;
import info.bukova.isspst.ui.BoolConverter;
import info.bukova.isspst.ui.ListViewModel;

public class WorkgroupList extends ListViewModel<Workgroup> {

	@WireVariable
	private WorkgroupService workgroupService;
	@WireVariable
	private RoleService roleService;
	private WorkgroupTreeFactory treeFactory;
	private BoolConverter boolConverter;
	
	@Init
	public void init() {
		service = workgroupService;
		dataClass = Workgroup.class;
		formZul = "workgroupForm.zul";
		dataFilter = new WorkgroupFilter(getFilterTemplate());
		treeFactory = new WorkgroupTreeFactory();
		treeFactory.setWorkgroupService(workgroupService);
		boolConverter = new BoolConverter();
	}
	
	public TreeModel<TreeNode<Member>> getWorkgroupTreeModel() {
		if (getDataBean() != null) {
			return treeFactory.createTreeModel(getDataBean());
		}
		
		return null;
	}
	
	@NotifyChange({"dataBean", "workgroupTreeModel", "ableToDelete", "workgroupRoles"})
	public void setDataBean(Workgroup data) {
		super.setDataBean(data);
	}

	@Override
	@GlobalCommand
	@NotifyChange({ "dataList", "dataBean", "workgroupTreeModel", "ableToDelete", "workgroupRoles" })
	public void refresh() {
		super.refresh();
	}

	@Override
	@Command
	@NotifyChange({ "filter", "dataList", "dataBean", "workgroupTreeModel", "workgroupRoles" })
	public void filter() {
		super.filter();
	}
	
	public BoolConverter getBoolConverter() {
		return boolConverter;
	}
	
	public List<Role> getWorkgroupRoles() {
		if (getDataBean() != null && getDataBean().isCentre()) {
			return roleService.getCentreRoles();
		} else if (getDataBean() != null) {
			return roleService.getWorkgroupRoles();
		}
		
		return null;
	}
	
}
