package com.rjconsultores.ventaboletos.web.utilerias.render;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;

import com.rjconsultores.ventaboletos.entidad.Corrida;
import com.rjconsultores.ventaboletos.enums.StatusFlexBus;
import com.rjconsultores.ventaboletos.service.CorridaService;
import com.rjconsultores.ventaboletos.web.utilerias.spring.AppContext;

/**
 * 
 * @author Valdir Cordeiro
 */
public class RenderCorridaFlexBus implements ListitemRenderer {
	
	private String buscarOcupacao(Corrida corrida) {
		CorridaService corridaService = (CorridaService) AppContext.getApplicationContext().getBean("corridaService");
		Integer ocupacao = corridaService.buscarOcupacaoCorrida(corrida);
		return ocupacao == null ? "0" : ocupacao.toString();
	}
	
	public void render(Listitem lstm, Object o) throws Exception {
		Corrida corrida = (Corrida) o;

		Listcell lc = new Listcell(corrida.getId().getCorridaId().toString());
		lc.setParent(lstm);
		
		SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy");
		lc = new Listcell(dt.format(corrida.getId().getFeccorrida()));
		lc.setParent(lstm);
		
		dt = new SimpleDateFormat("HH:mm");
		lc = new Listcell(dt.format(corrida.getFechorsalida()));
		lc.setParent(lstm);

		lc = new Listcell(corrida.getOcupacaoMinima().toString());
		lc.setParent(lstm);

		lc = new Listcell(buscarOcupacao(corrida));
		lc.setParent(lstm);
		
		lc = new Listcell(corrida.getHorasParaConfirmacao() + ":" + corrida.getMinutosParaConfirmacao());
		lc.setParent(lstm);
		
		String tempoPraConfirmacao = buscarTempoPraConfirmacao(corrida);
		lc = new Listcell(tempoPraConfirmacao);
		lc.setParent(lstm);
		
		//Status corrida
		String status = StatusFlexBus.buscarStatus(corrida.getStatusFlexBus());
		lc = new Listcell( status == null ? " - " : status);
		lc.setParent(lstm);

		lstm.setAttribute("data", corrida);
	}
	
	private String buscarTempoPraConfirmacao(Corrida corrida) {
		try {
			Calendar dataCorrida = Calendar.getInstance();
			dataCorrida.setTime(corrida.getFechorsalida());

			dataCorrida.add(Calendar.MINUTE, -corrida.getMinutosParaConfirmacao());
			dataCorrida.add(Calendar.HOUR, -corrida.getHorasParaConfirmacao());
			
			Date dataAtual = Calendar.getInstance().getTime();

			Date dataCorrida2 = dataCorrida.getTime();
	
			long diff = dataCorrida2.getTime() - dataAtual.getTime();
			long diffHours = (int) (diff / (60 * 60 * 1000) % 24);
			long diffMinutes = diff / (60 * 1000) % 60;
			long diffDays = diff / (24 * 60 * 60 * 1000);

			if (diffDays > 0) {
				diffHours = (diffHours + (diffDays * 24));
			}
			
			if(diffHours < 0 || diffMinutes < 0) {
				return "00:00";
			}

			return String.format("%02d", diffHours) + ":" + String.format("%02d", diffMinutes);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return "00:00";
	}
}
