package br.com.centralit.citcorpore.ajaxForms;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.centralit.citajax.html.AjaxFormAction;
import br.com.centralit.citajax.html.DocumentHTML;
import br.com.centralit.citcorpore.bean.ServicoContratoDTO;
import br.com.centralit.citcorpore.bean.ServicoDTO;
import br.com.centralit.citcorpore.negocio.AcordoNivelServicoService;
import br.com.centralit.citcorpore.negocio.AcordoServicoContratoService;
import br.com.centralit.citcorpore.negocio.ServicoContratoService;
import br.com.centralit.citcorpore.negocio.ServicoService;
import br.com.centralit.citcorpore.util.ComparatorUtil;
import br.com.centralit.citcorpore.util.Enumerados.ParametroSistema;
import br.com.centralit.citcorpore.util.Enumerados.ServiceDemandType;
import br.com.centralit.citcorpore.util.ParametroUtil;
import br.com.centralit.citcorpore.util.WebUtil;
import br.com.citframework.integracao.core.PageRequest;
import br.com.citframework.integracao.core.Pageable;
import br.com.citframework.service.ServiceLocator;
import br.com.citframework.util.UtilI18N;
import br.com.citframework.util.UtilStrings;

public class ListaServicosContrato extends AjaxFormAction {

	@Override
	public Class<ServicoContratoDTO> getBeanClass() {
		return ServicoContratoDTO.class;
	}

	@Override
	@SuppressWarnings("rawtypes")
	public void load(DocumentHTML document, HttpServletRequest request,	HttpServletResponse response) throws Exception {
		WebUtil.validarSeUsuarioEstaNaSessao(request, document);
		String pathInfo = request.getRequestURI();
		String ext = "";
		ext = getObjectExt(pathInfo);
		ext = ext.replaceAll("#", "");
		Integer attrPaginacao = 0;
		Integer paginaSelecionada = 0;
		Integer idContrato;
		String campoPesquisa="";
		ServicoContratoDTO servicoContratoDTO = (ServicoContratoDTO) document.getBean();
		
		if ("load".equalsIgnoreCase(ext)) {
			idContrato = Integer.parseInt(UtilStrings.decodeCaracteresEspeciais(request.getParameter("idContrato")));
			servicoContratoDTO.setIdContrato(idContrato);
			
			if (UtilStrings.isNotVazio(request.getParameter("paginacao"))) {
				attrPaginacao = Integer.parseInt(UtilStrings.decodeCaracteresEspeciais(request.getParameter("paginacao")));
			}
			
			if (request.getParameter("pesquisa") != null && request.getParameter("pesquisa") != "") {
				campoPesquisa = UtilStrings.decodeCaracteresEspeciais(request.getParameter("pesquisa"));
				idContrato = Integer.parseInt(UtilStrings.decodeCaracteresEspeciais(request.getParameter("idContrato")));
				servicoContratoDTO.setIdContrato(idContrato);
			}
		}
		
		Integer itensPorPagina = Integer.parseInt(ParametroUtil.getValorParametroCitSmartHashMap(ParametroSistema.QUANT_RETORNO_PESQUISA, "5"));
		
		Integer attrPaginaSelecionada = 0;
		try {
			attrPaginaSelecionada = new Integer(request.getSession(true).getAttribute("paginaSelecionada").toString());
		} catch(Exception e) {}
		
		Integer attrTotalPag = 1;
		try {
			attrTotalPag = new Integer(request.getSession(true).getAttribute("totalPag").toString());
		} catch(Exception e) {}
		
		if (attrPaginacao == 1) { // Próxima página
			
			paginaSelecionada = attrPaginaSelecionada + 1;
			
			// Quando já está na última página
			if (paginaSelecionada >= attrTotalPag) {
				paginaSelecionada = attrTotalPag;
			}
		} else if (attrPaginacao ==  -1) { //Página anterior
			paginaSelecionada = attrPaginaSelecionada - 1;
		} else if (attrPaginacao == 0) { // Primeira página
			paginaSelecionada = 1;
		} else { // Última página
			paginaSelecionada = attrTotalPag;
		}

		if (paginaSelecionada == 0) {
			paginaSelecionada = 1;
		}
		
		request.getSession(true).setAttribute("paginaSelecionada", paginaSelecionada);
		
		ServicoContratoService serviceContratoService = (ServicoContratoService) ServiceLocator.getInstance().getService(ServicoContratoService.class, null);
		ServicoService servicoService = (ServicoService) ServiceLocator.getInstance().getService(ServicoService.class, null);
		AcordoNivelServicoService acordoNivelServicoService = (AcordoNivelServicoService) ServiceLocator.getInstance().getService(AcordoNivelServicoService.class, null);
		AcordoServicoContratoService acordoServicoContratoService = (AcordoServicoContratoService) ServiceLocator.getInstance().getService(AcordoServicoContratoService.class, null);
		
		Pageable pageable = new PageRequest(paginaSelecionada - 1, itensPorPagina);
		
		Collection<ServicoContratoDTO> colServicosContrato = serviceContratoService.findByIdContratoPaginada(servicoContratoDTO, pageable, campoPesquisa);
		
		request.getSession(true).setAttribute("totalPag", servicoContratoDTO.getTotalPagina());
		request.getSession(true).setAttribute("totalItens", (servicoContratoDTO.getTotalItens() ));
		
		List<ServicoContratoDTO> colFinal = new ArrayList<ServicoContratoDTO>();
		if (colServicosContrato != null){
			for(Iterator<ServicoContratoDTO> it = colServicosContrato.iterator(); it.hasNext();){
				ServicoContratoDTO servicoContratoAux = (ServicoContratoDTO)it.next();
				if (servicoContratoAux.getDeleted() != null && !servicoContratoAux.getDeleted().equalsIgnoreCase("N")){
				    continue;
				}
				if (servicoContratoAux.getIdServico() != null){
					ServicoDTO servicoDto = new ServicoDTO();
					servicoDto.setIdServico(servicoContratoAux.getIdServico());
					servicoDto = (ServicoDTO) servicoService.restore(servicoDto);
					if (servicoDto != null){
						if (servicoDto.getDeleted() != null && !servicoDto.getDeleted().equalsIgnoreCase("N")){
						    continue;
						}		
						servicoContratoAux.setTemSLA(false);
						servicoContratoAux.setNomeServico(servicoDto.getNomeServico());
						servicoContratoAux.setServicoDto(servicoDto);
						servicoContratoAux.setSituacaoServico(servicoDto.getIdSituacaoServico());
						if (servicoDto.getIdTipoDemandaServico() != null){
							ServiceDemandType tipoDemandaServico = ServiceDemandType.fromId(servicoDto.getIdTipoDemandaServico());
						    if (tipoDemandaServico != null){
						    	servicoContratoAux.setNomeTipoDemandaServico(UtilI18N.internacionaliza(request, tipoDemandaServico.getI18NKey()));
						    }
						}
						Collection col = acordoNivelServicoService.findByIdServicoContrato(servicoContratoAux.getIdServicoContrato());
						Collection colVincs = acordoServicoContratoService.findByIdServicoContrato(servicoContratoAux.getIdServicoContrato());		
						if ((col != null && col.size() > 0) || (colVincs != null && colVincs.size() > 0)){
							servicoContratoAux.setTemSLA(true);	
						}
						colFinal.add(servicoContratoAux);
					}
				}
			}
		}
		
		Collections.sort(colFinal, ComparatorUtil.getComparatorPorNomeServico());
		request.setAttribute("listaServicos", colFinal);
	}
	
	public String getObjectExt(String path) {
		String strResult = "";
		for (int i = path.length() - 1; i >= 0; i--) {
			if (path.charAt(i) == '.') {
				return strResult;
			} else {
				strResult = path.charAt(i) + strResult;
			}
		}
		return strResult;
	}

}
