/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rjconsultores.ventaboletos.web.gui.controladores.catalogos;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.event.InputEvent;

import com.rjconsultores.ventaboletos.utilerias.StringHelper;
import com.rjconsultores.ventaboletos.web.utilerias.MyGenericForwardComposer;
import com.rjconsultores.ventaboletos.web.utilerias.MyListbox;
import com.rjconsultores.ventaboletos.web.utilerias.menu.ItemMenuSistema;
import com.rjconsultores.ventaboletos.web.utilerias.render.RenderSearchMenu;

@Controller("searchMenuController")
@Scope("prototype")
public class SearchMenuController extends MyGenericForwardComposer {

	private static Logger log = LogManager.getLogger(SearchMenuController.class);
	private HashMap<String, ItemMenuSistema> menuItems;
	private MyListbox searchResultList;

	@SuppressWarnings("unchecked")
	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		searchResultList.setItemRenderer(new RenderSearchMenu());
		menuItems = (HashMap<String, ItemMenuSistema>) Executions.getCurrent().getArg().get("menuItems");
		searchResultList.setData(new ArrayList<ItemMenuSistema>());
	}

	public void onChanging$bd(InputEvent ie) {
		 List<ItemMenuSistema> list = new ArrayList<ItemMenuSistema>();
		if (ie.getValue().length() > 0) {
			searchResultList.clear();
			String searchValue = StringHelper.replaceAcento(ie.getValue().toLowerCase());
			for (Map.Entry<String, ItemMenuSistema> entry : menuItems.entrySet()) {
				String key = StringHelper.replaceAcento(entry.getKey().toLowerCase());
				if (key.contains(searchValue)) {
					ItemMenuSistema value = entry.getValue();
					list.add(value);
				}
			}
			Collections.sort(list, new Comparator<ItemMenuSistema>() {
				@Override
				public int compare(ItemMenuSistema o1, ItemMenuSistema o2) {
					return o1.getDescItemMenu().compareTo(o2.getDescItemMenu());
				}
			});
			searchResultList.setData(list);
		}
	}

	public void onSelect$searchResultList(ForwardEvent ev) {
		this.closeWindow();
		ItemMenuSistema value = (ItemMenuSistema) searchResultList.getSelected();
		value.ejecutar();
	}

}
