package br.com.centralit.citcorpore.ajaxForms;

import java.util.Collection;

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

import org.apache.commons.lang3.StringUtils;

import br.com.centralit.citajax.html.AjaxFormAction;
import br.com.centralit.citajax.html.DocumentHTML;
import br.com.centralit.citajax.html.HTMLForm;
import br.com.centralit.citajax.html.HTMLTable;
import br.com.centralit.citcorpore.bean.GrupoDTO;
import br.com.centralit.citcorpore.negocio.GrupoService;
import br.com.centralit.citcorpore.util.CITCorporeUtil;
import br.com.centralit.citcorpore.util.WebUtil;
import br.com.centralit.citsmart.rest.bean.RestDomainDTO;
import br.com.centralit.citsmart.rest.bean.RestOperationDTO;
import br.com.centralit.citsmart.rest.bean.RestParameterDTO;
import br.com.centralit.citsmart.rest.bean.RestPermissionDTO;
import br.com.centralit.citsmart.rest.service.RestDomainService;
import br.com.centralit.citsmart.rest.service.RestOperationService;
import br.com.centralit.citsmart.rest.service.RestParameterService;
import br.com.centralit.citsmart.rest.service.RestPermissionService;
import br.com.citframework.service.ServiceLocator;
import br.com.citframework.util.UtilI18N;

/**
 * @author CentralIT
 *
 */
public class OperacaoRest extends AjaxFormAction {

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

    @Override
    public void load(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws Exception {

		CITCorporeUtil.limparFormulario(document);
		document.focusInFirstActivateField(null);

		this.retoreGUIToDefault(document);

		final RestParameterService parametrosService = (RestParameterService) ServiceLocator.getInstance().getService(RestParameterService.class, WebUtil.getUsuarioSistema(request));
		request.setAttribute("colParametros", parametrosService.list());

		if (StringUtils.isNotBlank(request.getParameter("idRestOperation")) && StringUtils.isNotBlank(request.getParameter("editar")) && StringUtils.isNotBlank(request.getParameter("iframe"))) {
			if (request.getParameter("idRestOperation") != null && request.getParameter("idRestOperation").toString() != null) {
				HTMLForm form = document.getForm("form");
				form.setValue("idRestOperation", request.getParameter("idRestOperation"));
				form.setValue("editar", request.getParameter("editar"));
				RestOperationDTO restOperationDTO = (RestOperationDTO) document.getBean();

				if (restOperationDTO != null && restOperationDTO.getIdRestOperation() != null) {
					this.restore(document, request, response);

					if (restOperationDTO.getEditar() != null && restOperationDTO.getEditar().equalsIgnoreCase("RO")) {
						this.convertFieldsToOnlyReady(document, request, response, restOperationDTO);
					} else {
						document.executeScript("parent.JANELA_AGUARDE_MENU.hide()");
					}
				}
				if (request.getParameter("iframe") != null && request.getParameter("iframe").toString() != null) {
					form.setValue("isPaginaExterna", request.getParameter("iframe"));

					document.executeScript("$('button[name=\"btnLimpar\"]').hide();");
					document.executeScript("$('#linkTabs2').closest('li').remove();");
				}
			}
		}
    }

	private RestOperationDTO findByIdRestOperation(Integer idRestOperationDTO) throws Exception {
		final RestOperationService restOperationService = (RestOperationService) ServiceLocator.getInstance().getService(RestOperationService.class, null);
		RestOperationDTO restOperation = restOperationService.findByIdRestOperation(idRestOperationDTO);

		return restOperation;
	}

	private void convertFieldsToOnlyReady(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response, RestOperationDTO restOperationDTO) throws Exception {
		RestOperationDTO restOperation = this.findByIdRestOperation(restOperationDTO.getIdRestOperation());

		if (restOperation.getJavaClass() != null && !restOperation.getJavaClass().isEmpty()) {
			document.executeScript("$('#javaDiv').show();");
			document.executeScript("$('#javaScriptDiv').hide();");

		} else if (restOperation.getJavaScript() != null && !restOperation.getJavaScript().isEmpty()) {
			document.executeScript("$('#javaDiv').hide();");
			document.executeScript("$('#javaScriptDiv').show();");
		}

		document.executeScript("$('#name').attr('disabled', 'disabled');");
		document.executeScript("$('#description').attr('disabled', 'disabled');");
		document.executeScript("$('#javaScript').attr('disabled', 'disabled');");
		document.executeScript("$('#javaClass').attr('disabled', 'disabled');");
		document.executeScript("$('#btnNovoParametro').attr('disabled', 'disabled');");
		document.executeScript("$('.inputRadio').attr('disabled', 'disabled')");

		document.executeScript("$('button').hide();");

		document.executeScript("$('#divGridParametros textarea').attr('disabled', 'disabled');");
		document.executeScript("$('#divGridParametros select').attr('disabled', 'disabled');");
		document.executeScript("$('#divGridParametros img').hide();");

		document.executeScript("$('#divGrupo img').hide();");
		document.executeScript("$('#linkTabs2').closest('li').remove();");
		document.executeScript("$('#tabelaGrupo tr').css('cursor','');");

		document.executeScript("parent.JANELA_AGUARDE_MENU.hide()");
	}

	@SuppressWarnings("unchecked")
	public void save(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        try {
            final RestOperationDTO restDTO = (RestOperationDTO) document.getBean();

            final Collection<RestPermissionDTO> colGrupos = br.com.citframework.util.WebUtil
                    .deserializeCollectionFromRequest(RestPermissionDTO.class, "colGrupoSerialize", request);
            if (colGrupos != null) {
                for (final RestPermissionDTO restPermissionDTO : colGrupos) {
                    restPermissionDTO.setIdGroup(restPermissionDTO.getIdGrupo());
                }
            }

            final Collection<RestDomainDTO> colDominios = br.com.citframework.util.WebUtil
                    .deserializeCollectionFromRequest(RestDomainDTO.class, "colParametros_Serialize", request);
            restDTO.setColDominios(colDominios);

            final RestOperationService restService = (RestOperationService) ServiceLocator.getInstance().getService(RestOperationService.class, null);

            restDTO.setColGrupos(colGrupos);

            if (restDTO.getIdRestOperation() != null) {
                restService.update(restDTO);
                document.alert(UtilI18N.internacionaliza(request, "MSG06"));
            } else {
                restService.create(restDTO);
                document.alert(UtilI18N.internacionaliza(request, "MSG05"));
            }
            this.retoreGUIToDefault(document);

			if (restDTO.isPaginaExterna() != null && restDTO.isPaginaExterna()) {
				document.executeScript("parent.fechaModalWebService();");
			}
		} finally {
			document.executeScript("JANELA_AGUARDE_MENU.hide();");
        }
    }

    public void gravarParametro(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        final RestOperationDTO restDTO = (RestOperationDTO) document.getBean();

        RestParameterDTO restParamDTO = new RestParameterDTO();
        restParamDTO.setDescription(restDTO.getDescriptionParameter());
        restParamDTO.setIdentifier(restDTO.getIdentifier());
        if (restParamDTO.getIdentifier().indexOf(" ") >= 0) {
            document.alert(UtilI18N.internacionaliza(request, "parametros.formatoIdentificador"));
            return;
        }
        restParamDTO.setIdentifier(restParamDTO.getIdentifier().toUpperCase());

        final RestParameterService restService = (RestParameterService) ServiceLocator.getInstance().getService(RestParameterService.class, null);

        if (restParamDTO.getIdRestParameter() != null) {
            restService.update(restParamDTO);
        } else {
            restParamDTO = restService.create(restParamDTO);
            document.executeScript("adicionaParam(" + restParamDTO.getIdRestParameter() + ",\"" + restParamDTO.getDescription() + "\")");
        }
        final HTMLForm form = document.getForm("formCadastroParam");
        form.clear();
        document.executeScript("$(\"#POPUP_PARAMETRO\").dialog(\"close\")");
    }

    /**
     * @param document
     * @param request
     * @param response
     * @throws Exception
     *             Metodo colocar status Inativo quando for solicitado a exclusão do usuario.
     */
    public void delete(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        final RestOperationDTO restDTO = (RestOperationDTO) document.getBean();

        final RestOperationService restService = (RestOperationService) ServiceLocator.getInstance().getService(RestOperationService.class, null);

        if (restDTO.getIdRestOperation().intValue() > 0) {
            restService.delete(restDTO);
        }

        final HTMLForm form = document.getForm("form");
        form.clear();
        document.alert(UtilI18N.internacionaliza(request, "MSG07"));

        document.executeScript("limpar()");
    }

    public void restore(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        try {
            RestOperationDTO restDTO = (RestOperationDTO) document.getBean();
            final RestOperationService restService = (RestOperationService) ServiceLocator.getInstance().getService(RestOperationService.class, null);
            final RestPermissionService restPermissionService = (RestPermissionService) ServiceLocator.getInstance().getService(RestPermissionService.class, null);
            final GrupoService grupoService = (GrupoService) ServiceLocator.getInstance().getService(GrupoService.class, null);
            Integer id = null;

            restDTO = (RestOperationDTO) restService.restore(restDTO);
            id = restDTO.getIdRestOperation();

            document.executeScript("deleteAllRows()");
            final Collection<RestPermissionDTO> colPermissoes = restPermissionService.findByIdOperation(id);
            if (colPermissoes != null) {
                for (final RestPermissionDTO restPermDto : colPermissoes) {
                    restPermDto.setIdGrupo(restPermDto.getIdGroup());
                    GrupoDTO grupoDto = new GrupoDTO();
                    grupoDto.setIdGrupo(restPermDto.getIdGroup());
                    grupoDto = (GrupoDTO) grupoService.restore(grupoDto);
                    if (grupoDto != null) {
                        restPermDto.setSigla(grupoDto.getSigla());
                    }
                }
                final HTMLTable table = document.getTableById("tabelaGrupo");
                table.deleteAllRows();
                table.addRowsByCollection(colPermissoes, new String[] {"", "idGrupo", "sigla"}, null, null, new String[] {"gerarButtonDeleteGrupo"}, null, null);
            }

            final HTMLForm form = document.getForm("form");
            form.clear();
            form.setValues(restDTO);

            final RestDomainService restDomainService = (RestDomainService) ServiceLocator.getInstance().getService(RestDomainService.class, null);
            final Collection<RestDomainDTO> colParametros = restDomainService.findByIdRestOperation(restDTO.getIdRestOperation());
            document.executeScript("GRID_PARAMETROS.deleteAllRows();");
            if (colParametros != null) {
                int i = 0;
                for (final RestDomainDTO dominioDto : colParametros) {
                	String value = dominioDto.getValue();
                	value = value.replaceAll("\\n","#13#");
                	value = value.replaceAll("'","#39#");
                	dominioDto.setValue(value);
                	
                    i++;
                    document.executeScript("GRID_PARAMETROS.addRow()");
                    dominioDto.setSequencia(i);
                    document.executeScript("seqParametro = NumberUtil.zerosAEsquerda(" + i + ",5)");
                    document.executeScript("exibeParametro('" + br.com.citframework.util.WebUtil.serializeObject(dominioDto, WebUtil.getLanguage(request)) + "')");
                }
            }
        } finally {
            document.executeScript("JANELA_AGUARDE_MENU.hide()");
        }
    }

    private void retoreGUIToDefault(final DocumentHTML document) throws Exception {
        final HTMLForm form = document.getForm("form");
        form.clear();
        final HTMLTable tabelaGrupo = document.getTableById("tabelaGrupo");
        tabelaGrupo.deleteAllRows();
        document.executeScript("GRID_PARAMETROS.deleteAllRows();");
    }

}
