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

import java.util.ArrayList;
import java.util.List;

import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;

/**
 * 
 * @author gleimar
 */
public class MyListbox extends Listbox {

	private static final long serialVersionUID = 1L;
	private Object selected = null;
	private ListModelList modelList = new ListModelList();

	public void setData(List<? extends Object> data) {

		this.modelList.clear();
		this.modelList.addAll(data);

		super.setModel(modelList);
	}

	public MyListbox() {
		super.setModel(modelList);
		setVflex(Boolean.TRUE);
	}

	public boolean addItemNovo(Object item) {
		try {
			this.modelList.add(item);
			super.setModel(modelList);

			return Boolean.TRUE;
		} catch (Exception e) {
			return Boolean.FALSE;
		}
	}

	/**
	 * Adiciona um item na lista caso ele não esteja presente na lista
	 * 
	 * 
	 * @param item
	 * @return - True se o item foi adicionado
	 * @deprecated - Use o método addItemNovo
	 * 
	 */
	@Deprecated
	public boolean addItem(Object item) {
		boolean ok = false;
		if (!this.modelList.contains(item)) {
			ok = this.modelList.add(item);
		}

		return ok;
	}

	/**
	 * Atualiza se o item está presente na lista. Caso não esteja presente, o item é adicionado.
	 * 
	 * @param item
	 */
	public void updateItem(Object item) {
		if (this.modelList.contains(item)) {
			this.modelList.set(modelList.indexOf(item), item);
		} else {
			this.addItem(item);
		}
	}

	public void removeItem(Object item) {
		this.modelList.remove(item);
	}

	public Object removeSelectedItem() {
		int index = this.getSelectedIndex();

		if (index != -1) {
			return this.modelList.remove(index);
		}

		return null;

	}

	public Object getSelected() {
		int index = this.getSelectedIndex();
		selected = null;
		if (index != -1) {
			selected = this.modelList.get(index);
		}

		return this.selected;
	}

	public List<Object> getSelectedsItens() {
		int index = this.getSelectedIndex();
		int qtd = this.getSelectedCount();
		List<Object> selecteds = new ArrayList<Object>();
		if (index != -1) {
			for (int i = 0; i < qtd; i++) {
				selecteds.add(this.modelList.get(index + i));
			}
		}

		return selecteds;
	}

	public int getSize() {
		return (modelList == null) ? 0 : modelList.getSize();
	}

	public Object[] getData() {
		return this.modelList.toArray();
	}

	public List getListData() {
		return this.modelList;
	}
}
