package info.bukova.isspst.ui.users;

import info.bukova.isspst.Constants;
import info.bukova.isspst.Module;
import info.bukova.isspst.ModuleUtils;
import info.bukova.isspst.data.Permission;
import info.bukova.isspst.data.Role;
import info.bukova.isspst.data.User;
import info.bukova.isspst.filters.UserFilter;
import info.bukova.isspst.services.users.UserService;
import info.bukova.isspst.ui.ListViewModel;
import info.bukova.isspst.ui.renderers.UserItemRenderer;
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 java.util.ArrayList;
import java.util.List;

public class UsersList extends ListViewModel<User> {
	
	@WireVariable
	private UserService userService;
	private UserItemRenderer itemRenderer;
	
	@Init
	public void init() {
		service = userService;
		dataClass = User.class;
		formZul = "userForm.zul";
		dataFilter = new UserFilter(getFilterTemplate());
		itemRenderer = new UserItemRenderer();
	}
	
	public List<Module> getModules() {
		return ModuleUtils.getActiveModules();
	}
	
	@Override
	@NotifyChange({"permissions", "dataBean", "ableToDelete"})
	public void setDataBean(User user) {
		super.setDataBean(user);
	}
	
	@Override
	@GlobalCommand
	@NotifyChange({"dataList", "dataBean", "permissions", "ableToDelete"})
	public void refresh() {
		super.refresh();
	}
	
	public List<Permission> getPermissions() {
		if (getDataBean() == null) {
			return null;
		}
		List<Permission> ret = new ArrayList<Permission>();
		
		for (Role r : getDataBean().getAuthorities()) {
			for (Permission p : r.getPermissions()) {
				boolean addPerm = true;
				for (Permission chPerm : ret) {
					if (chPerm.getAuthority().equals(p.getAuthority()) 
							&& chPerm.getModule().equals(p.getModule())) {
						addPerm = false;
					}
				}
				if (addPerm) {
					ret.add(p);
				}
			}
		}
		
		return ret;
	}

	@Override
	public boolean isAbleToDelete() {
		
		if (!super.isAbleToDelete())
		{
			return false;
		}
		
		if (getDataBean().getUsername().equals(Constants.DEF_ADMIN))
		{
			return false;
		}
		
		return true;
	}

	public UserItemRenderer getItemRenderer() {
		return itemRenderer;
	}
}
