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

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.util.resource.Labels;
import org.zkoss.zhtml.Messagebox;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Paging;
import org.zkoss.zul.Textbox;

import com.rjconsultores.ventaboletos.entidad.Empresa;
import com.rjconsultores.ventaboletos.entidad.Parada;
import com.rjconsultores.ventaboletos.entidad.Pricing;
import com.rjconsultores.ventaboletos.entidad.Ruta;
import com.rjconsultores.ventaboletos.service.EmpresaService;
import com.rjconsultores.ventaboletos.service.ParadaService;
import com.rjconsultores.ventaboletos.service.PricingService;
import com.rjconsultores.ventaboletos.service.RutaService;
import com.rjconsultores.ventaboletos.utilerias.UsuarioLogado;
import com.rjconsultores.ventaboletos.web.utilerias.MyGenericForwardComposer;
import com.rjconsultores.ventaboletos.web.utilerias.MyListbox;
import com.rjconsultores.ventaboletos.web.utilerias.paginacion.HibernateSearchObject;
import com.rjconsultores.ventaboletos.web.utilerias.paginacion.PagedListWrapper;
import com.rjconsultores.ventaboletos.web.utilerias.render.RenderPricing;

/**
 * 
 * @author Rafius
 */
@Controller("busquedaPricingController")
@Scope("prototype")
public class BusquedaPricingController extends MyGenericForwardComposer {

	private static final long serialVersionUID = 1L;
	@Autowired
	private transient PagedListWrapper<Pricing> plwPricingPunto;
	@Autowired
	private PricingService pricingService;
	@Autowired
	private EmpresaService empresaService;
	@Autowired
	private RutaService rutaService;
	private MyListbox pricingList;
	private Paging pagingPricing;
	private List<Pricing> lsPricing;
	private List<Empresa> lsEmpresa;
	private List<Ruta> lsRuta;
	private Combobox cmbEmpresa;
	private Textbox txtNome;
	private Datebox fechaInicio;
	private Datebox fechaFin;
	private Checkbox chkBuscarInativos;
	private Combobox cmbRuta;
	private Combobox cmbOrigen;
	private Combobox cmbDestino;
	@Autowired
	private ParadaService paradaService;
	
	private static Logger log = Logger.getLogger(BusquedaPricingController.class);

	public List<Pricing> getLsPricing() {
		return lsPricing;
	}

	public void setLsPricing(List<Pricing> lsPricing) {
		this.lsPricing = lsPricing;
	}

	public Paging getPagingPricing() {
		return pagingPricing;
	}

	public void setPagingPricing(Paging pagingPricing) {
		this.pagingPricing = pagingPricing;
	}

	public MyListbox getPricingList() {
		return pricingList;
	}

	public void setPricingList(MyListbox pricingList) {
		this.pricingList = pricingList;
	}

	public PricingService getPricingService() {
		return pricingService;
	}

	public void setPricingService(PricingService pricingService) {
		this.pricingService = pricingService;
	}

	public EmpresaService getEmpresaService() {
		return empresaService;
	}

	public void setEmpresaService(EmpresaService empresaService) {
		this.empresaService = empresaService;
	}

	public List<Empresa> getLsEmpresa() {
		return lsEmpresa;
	}

	public void setLsEmpresa(List<Empresa> lsEmpresa) {
		this.lsEmpresa = lsEmpresa;
	}

	public Textbox getTxtNome() {
		return txtNome;
	}

	public void setTxtNome(Textbox txtNome) {
		this.txtNome = txtNome;
	}

	public Datebox getFechaInicio() {
		return fechaInicio;
	}

	public void setFechaInicio(Datebox fechaInicio) {
		this.fechaInicio = fechaInicio;
	}

	public Datebox getFechaFin() {
		return fechaFin;
	}

	public void setFechaFin(Datebox fechaFin) {
		this.fechaFin = fechaFin;
	}

	public RutaService getRutaService() {
		return rutaService;
	}

	public void setRutaService(RutaService rutaService) {
		this.rutaService = rutaService;
	}

	public List<Ruta> getLsRuta() {
		return lsRuta;
	}

	public void setLsRuta(List<Ruta> lsRuta) {
		this.lsRuta = lsRuta;
	}

	public Combobox getCmbRuta() {
		return cmbRuta;
	}

	public void setCmbRuta(Combobox cmbRuta) {
		this.cmbRuta = cmbRuta;
	}

	@Override
	public void doAfterCompose(Component comp) throws Exception {

		lsEmpresa = UsuarioLogado.getUsuarioLogado().getEmpresa();
			
		super.doAfterCompose(comp);

		pricingList.setItemRenderer(new RenderPricing());
		pricingList.addEventListener("onDoubleClick", new EventListener() {

			@Override
			public void onEvent(Event event) throws Exception {
				Pricing pricing = (Pricing) pricingList.getSelected();
				verPricing(pricing);
			}
		});

		lsPricing = new ArrayList<Pricing>();

		refreshLista();
	}

	public void onChange$cmbEmpresa(Event ev) throws InterruptedException {
		
		Empresa empresa = (Empresa) (cmbEmpresa.getSelectedItem() != null ? cmbEmpresa.getSelectedItem().getValue() : null);
		
		if (empresa != null) {
			lsRuta = rutaService.obtenerPorEmpresa(empresa);
			lsRuta.add(rutaService.obtenerID(-1));
			BindingListModelList l = new BindingListModelList(lsRuta, true);
			cmbRuta.setModel(l);
		}

	}
	
	public void onClick$btnPesquisa(Event ev) throws InterruptedException {
		refreshLista();
	}

	public void onClick$btnRefresh(Event ev) {
		refreshLista();
	}

	public void onClick$btnNovo(Event ev) {
		verPricing(new Pricing());
	}

	private void refreshLista() {
		
		Empresa empresa = (Empresa) (cmbEmpresa.getSelectedItem() != null ? cmbEmpresa.getSelectedItem().getValue() : null);
		Ruta ruta = (Ruta) (cmbRuta.getSelectedItem() != null ? cmbRuta.getSelectedItem().getValue() : null);
		Parada origen = null;
		
		if (cmbOrigen.getSelectedItem() == null) {
			List<Parada> lsParadaOri = paradaService.buscar(cmbOrigen.getText().toUpperCase());
			if (!lsParadaOri.isEmpty()) {
				origen = lsParadaOri.get(0);
			}
		} else {
			origen = (Parada) cmbOrigen.getSelectedItem().getValue();
		}
		Parada destino = null;
		if (cmbDestino.getSelectedItem() == null) {
			List<Parada> lsParadaOri = paradaService.buscar(cmbDestino.getText().toUpperCase());
			if (!lsParadaOri.isEmpty()) {
				destino = lsParadaOri.get(0);
			}
		} else {
			destino = (Parada) cmbDestino.getSelectedItem().getValue();
		}

		HibernateSearchObject<Pricing> pricingSearch = new HibernateSearchObject<Pricing>(
				Pricing.class, pagingPricing.getPageSize());

		if (empresa != null) {
			pricingSearch.addFilterEqual("empresa", empresa);
		} else {
			pricingSearch.addFilterIn("empresa", lsEmpresa);
		}
		
		if (ruta != null && ruta.getRutaId() != -1) {
			pricingSearch.addFilterIn("pricingRutaList.ruta", ruta);
		}
		
		if (origen != null) {
			pricingSearch.addFilterIn("pricingMercadoList.origen", origen);
		}
		
		if (destino != null) {
			pricingSearch.addFilterIn("pricingMercadoList.destino", destino);
		}

		if (!txtNome.getValue().isEmpty()) {
			pricingSearch.addFilterILike("nombPricing", txtNome.getValue() + "%");
		}

		Calendar calendar = Calendar.getInstance();
		Calendar calendar1 = Calendar.getInstance();
		if ((fechaInicio.getValue() != null) && (fechaFin.getValue() != null)) {
			calendar.setTime(fechaInicio.getValue());
			calendar.set(Calendar.HOUR_OF_DAY, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);
			calendar.set(Calendar.MILLISECOND, 0);

			calendar1.setTime(fechaFin.getValue());
			calendar1.set(Calendar.HOUR_OF_DAY, 23);
			calendar1.set(Calendar.MINUTE, 59);
			calendar1.set(Calendar.SECOND, 59);
			calendar1.set(Calendar.MILLISECOND, 999);

			pricingSearch.addFilterGreaterOrEqual("pricingVigenciaList.fecinicioviaje", calendar.getTime());
			pricingSearch.addFilterLessOrEqual("pricingVigenciaList.fecfinviaje", calendar1.getTime());
		} else {
			if (fechaInicio.getValue() != null) {
				calendar.setTime(fechaInicio.getValue());
				calendar.set(Calendar.HOUR_OF_DAY, 0);
				calendar.set(Calendar.MINUTE, 0);
				calendar.set(Calendar.SECOND, 0);

				calendar1.setTime(fechaInicio.getValue());
				calendar1.set(Calendar.HOUR_OF_DAY, 23);
				calendar1.set(Calendar.MINUTE, 59);
				calendar1.set(Calendar.SECOND, 59);

				pricingSearch.addFilterGreaterThan("pricingVigenciaList.fecinicioviaje", calendar.getTime()).addFilterLessThan("pricingVigenciaList.fecinicioviaje", calendar1.getTime());
			} else if (fechaFin.getValue() != null) {
				calendar.setTime(fechaFin.getValue());
				calendar.set(Calendar.HOUR_OF_DAY, 0);
				calendar.set(Calendar.MINUTE, 0);
				calendar.set(Calendar.SECOND, 0);

				calendar1.setTime(fechaFin.getValue());
				calendar1.set(Calendar.HOUR_OF_DAY, 23);
				calendar1.set(Calendar.MINUTE, 59);
				calendar1.set(Calendar.SECOND, 59);
				pricingSearch.addFilterGreaterThan("pricingVigenciaList.fecfinviaje", calendar.getTime()).addFilterLessThan("pricingVigenciaList.fecfinviaje", calendar1.getTime());
			}
		}

		Boolean buscarInativos = chkBuscarInativos.isChecked();
		if (buscarInativos) {
			pricingSearch.addFilterEqual("activo", Pricing.INATIVO);
		} else {
			pricingSearch.addFilterEqual("activo", Pricing.ATIVO);
		}

		pricingSearch.addSortAsc("nombPricing");

		pricingSearch.addFetch("pricingVigenciaList");

		plwPricingPunto.init(pricingSearch, pricingList, pagingPricing);

		if (pricingList.getData().length == 0) {
			try {
				Messagebox.show(Labels.getLabel("MSG.ningunRegistro"), Labels
						.getLabel("busquedaPricingController.window.title"),
						Messagebox.OK, Messagebox.INFORMATION);
			} catch (InterruptedException ex) {
			}
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void verPricing(Pricing pricing) {
		if (pricing == null) {
			return;
		}

		Map args = new HashMap();
		args.put("pricing", pricing);
		args.put("gravarNovo", pricing.getPricingId() == null);
		args.put("pricingList", pricingList);
		args.put("buscarPricingInativosAtivos", chkBuscarInativos.isChecked() ? Pricing.INATIVO : Pricing.ATIVO);

		openWindow("/gui/pricing/editarPricing.zul",
				Labels.getLabel("editarPricingController.window.title"), args, MODAL);
	}

	public void onClick$btnApagar(Event ev) {
		try {
			Pricing p = (Pricing) pricingList.getSelected();
			if (p != null) {
				int resp = Messagebox.show(Labels.getLabel("editarPricingController.MSG.borrarPergunta"),
								Labels.getLabel("busquedaPricingController.window.title"),
								Messagebox.YES | Messagebox.NO,
								Messagebox.QUESTION);

				if (resp == Messagebox.YES) {
					pricingService.borrar(p);
					Messagebox.show(Labels.getLabel("editarPricingController.MSG.borrarOK"),
									Labels.getLabel("busquedaPricingController.window.title"),
									Messagebox.OK, Messagebox.INFORMATION);
					pricingList.removeItem(p);
				}
			} else {
				Messagebox.show(Labels.getLabel("editarPricingController.MSG.selectItem"),
								Labels.getLabel("busquedaPricingController.window.title"),
								Messagebox.OK, Messagebox.EXCLAMATION);
			}
		} catch (Exception ex) {
			log.error("Erro ao eliminar Pricing: " + ex);
		}
	}
}
