package br.com.centralit.citcorpore.ajaxForms;

import java.io.IOException;
import java.util.List;

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

import org.apache.commons.lang.StringEscapeUtils;
import org.json.JSONException;

import br.com.centralit.citajax.html.AjaxFormAction;
import br.com.centralit.citajax.html.DocumentHTML;
import br.com.centralit.citcorpore.bean.SmartReportDTO;
import br.com.centralit.citcorpore.bean.UsuarioDTO;
import br.com.centralit.citcorpore.negocio.SmartReportService;
import br.com.centralit.citcorpore.util.Enumerados;
import br.com.centralit.citcorpore.util.Enumerados.SimNao;
import br.com.centralit.citcorpore.util.Enumerados.TipoExibicaoRelatorio;
import br.com.centralit.citcorpore.util.LogoRel;
import br.com.centralit.citcorpore.util.WebUtil;
import br.com.centralit.citgerencial.bean.SmartReportParameterDTO;
import br.com.citframework.service.ServiceLocator;
import br.com.citframework.util.UtilI18N;
import br.com.citframework.util.UtilSmartReport;
import br.com.citframework.util.UtilStrings;

public class SmartReports extends AjaxFormAction {

	private SmartReportService smartReportService;

	@Override
	public void load(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}

		request.setAttribute("logo", LogoRel.getUrlLogoSistema());

		setReportCategories(document, request);
	}

	private void setReportCategories(DocumentHTML document, HttpServletRequest request) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}

		UsuarioDTO usuario = WebUtil.getUsuario(request);

		StringBuilder categoriaJson = new StringBuilder();

		int i = 0;
		int count = 0;
		categoriaJson.append("[");
		for(Enumerados.ReportCategories reportCategory : Enumerados.ReportCategories.values()) {
			count = getSmartReportService().getTotalByIdsGrupoUsuarioAndIdCategoria(usuario.getColGrupos(), reportCategory.getId());
			if(count > 0) {
				if(i > 0) {
					categoriaJson.append(", ");
				} else {
					i++;
				}
				categoriaJson.append("{");
				categoriaJson.append("	\"id\": \"" + reportCategory.getId() + "\", ");
				categoriaJson.append("	\"key\": \"" + reportCategory.getKey() + "\", ");
				categoriaJson.append("	\"icon\": \"" + reportCategory.getIcon() + "\", ");
				categoriaJson.append("	\"total\": \"" + count + "\"");
				categoriaJson.append("}");
			}
		}
		categoriaJson.append("]");

		document.executeScript("SMART_REPORTS.load.reportCategories(" + categoriaJson.toString() + ");");
	}

	public void carregaRelatoriosByIdCategoria(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}

		UsuarioDTO usuario = WebUtil.getUsuario(request);
		SmartReportDTO bean = (SmartReportDTO) document.getBean();

		List<SmartReportDTO> smartReportDTOs = this.getSmartReportService().findByIdsGrupoUsuarioAndIdCategoria(usuario.getColGrupos(), bean.getIdCategoria());
		String json = "[";
		int i = 0;
		for(SmartReportDTO smartReportDTO : smartReportDTOs) {
			if(i > 0) {
				json += ", ";
			} else {
				i++;
			}
			json += "{";
			json += "	\"idSmartReport\": \"" + smartReportDTO.getIdSmartReport() + "\", ";
			json += "	\"identificacao\": \"" + smartReportDTO.getIdentificacao() + "\"";
			json += "}";
		}
		json += "]";

		document.executeScript("SMART_REPORTS.set.reportCategoryItems(" + json + ")");
	}

	public void loadReport(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}

		SmartReportDTO bean = (SmartReportDTO) document.getBean();
		SmartReportDTO smartReportDTO = new SmartReportDTO();
		smartReportDTO.setIdSmartReport(bean.getIdSmartReport());

		smartReportDTO = getSmartReportService().restore(smartReportDTO);

		document.executeScript("$('#smart-reports-container-content .widget-head .widget-head-title').empty().append('" + smartReportDTO.getIdentificacao() + "')");
		document.executeScript("$('#smart-reports-container-content .header-print-title h3').empty().append('" + smartReportDTO.getIdentificacao() + "')");

		Boolean isExibirParametroIdEspecifico = false;

		try {
			isExibirParametroIdEspecifico = SimNao.SIM.name().equalsIgnoreCase(request.getParameter("exibirParametroIdEspecifico"));
		} catch (Exception e) {

		}

		if (!UtilStrings.isNullOrEmpty(smartReportDTO.getParametros()) || isExibirParametroIdEspecifico && TipoExibicaoRelatorio.ESPECIFICO.getIdentificador().equalsIgnoreCase(smartReportDTO.getTipoExibicao())) {
			loadReportParameters(document, request, smartReportDTO);
		} else if (smartReportDTO != null && smartReportDTO.getTipoConsulta() != null) {
			processReport(document, request, smartReportDTO);
		}

	}

	public void processReport(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}

		SmartReportDTO bean = (SmartReportDTO) document.getBean();
		SmartReportDTO smartReportDTO = new SmartReportDTO();
		smartReportDTO.setIdSmartReport(bean.getIdSmartReport());

		smartReportDTO = getSmartReportService().restore(smartReportDTO);

		processReport(document, request, smartReportDTO);
	}

	private void processReport(DocumentHTML document, HttpServletRequest request, SmartReportDTO smartReportDTO) throws IOException, Exception, JSONException {
		document.setBean(smartReportDTO);
		UtilSmartReport.processReport(document, request);
	}

	private void loadReportParameters(DocumentHTML document, HttpServletRequest request,
			SmartReportDTO smartReportDTO) throws Exception {
		List<SmartReportParameterDTO> smartReportParametroDTOs = UtilSmartReport.getReportParameters(smartReportDTO.getParametros());

		if (TipoExibicaoRelatorio.ESPECIFICO.getIdentificador().equalsIgnoreCase(smartReportDTO.getTipoExibicao())) {
			SmartReportParameterDTO specificParameter = new SmartReportParameterDTO();
			specificParameter.setDefaultValue("0");
			specificParameter.setDescription("smartReportGenerators.idEspecifico");
			specificParameter.setType("java.lang.Integer");
			specificParameter.setTypeHTML("text");
			specificParameter.setMandatory(Boolean.TRUE);
			specificParameter.setName("specificID");

			smartReportParametroDTOs.add(0, specificParameter);
		}

		String smartReportModalHtml = "";

		smartReportModalHtml += "<div class='smart-reports-container-params-fields clearfix'>" + UtilSmartReport.getHtmlReportParameters(request, smartReportParametroDTOs) + "</div>";
		smartReportModalHtml += "<button type='button' onclick='UtilSmartReport.process(" + smartReportDTO.getIdSmartReport() + ")' class='btn btn-params btn-default btn-mini pull-right'>"
				+ UtilI18N.internacionaliza(request, "citcorpore.comum.gerarRelatorio") + "</button>";
		smartReportModalHtml += "<button type='button' onclick='UtilSmartReport.cleanFilters(" + smartReportDTO.getIdSmartReport() + ")' class='btn btn-params btn-default btn-mini pull-right mr-5'>"
				+ UtilI18N.internacionaliza(request, "citcorpore.comum.limpar") + "</button>";

		document.executeScript("$('.div-smart-report-params').removeClass('hidden')");
		document.executeScript("$('.div-smart-report-params .body-params').empty().append('" + StringEscapeUtils.escapeJavaScript(smartReportModalHtml) + "')");
		document.executeScript("DEFINEALLPAGES_generateConfiguracaoCampos()");
		document.executeScript("$('.datepicker').datepicker();");
		document.executeScript("UtilSmartReport.afterLoadReport(" + smartReportDTO.getIdSmartReport() + ");");
	}

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

	private SmartReportService getSmartReportService() throws Exception {
		if (smartReportService == null) {
			smartReportService = (SmartReportService) ServiceLocator.getInstance().getService(SmartReportService.class, null);
		}

		return smartReportService;
	}

}