package br.com.centralit.citcorpore.ajaxForms;

import java.io.FileNotFoundException;
import java.util.Collection;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
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.citajax.html.HTMLForm;
import br.com.centralit.citajax.html.HTMLSelect;
import br.com.centralit.citcorpore.bean.ExternalConnectionDTO;
import br.com.centralit.citcorpore.bean.ImportarDadosDTO;
import br.com.centralit.citcorpore.negocio.ExternalConnectionService;
import br.com.centralit.citcorpore.negocio.ImportarDadosService;
import br.com.centralit.citcorpore.util.Enumerados.DriverJdbc;
import br.com.centralit.citcorpore.util.WebUtil;
import br.com.citframework.excecao.ServiceException;
import br.com.citframework.service.ServiceLocator;
import br.com.citframework.util.UtilI18N;

public class ExternalConnection extends AjaxFormAction {

	private ExternalConnectionService externalConnectionService;

	@Override
	public void load(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		HTMLSelect combo = document.getSelectById("tipo");
		inicializarCombo(combo, request);
		carregaComboDriver(document);
		document.focusInFirstActivateField(null);
	}

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

	public void save(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (testeConexaoComOsDadosInformados(document, request, response)) {
			salvar(document, request, response);
		} else {
			document.executeScript("confirmarSalvarDadosInvalidos()");
		}
	}

	public void salvar(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ExternalConnectionDTO conexoesDTO = (ExternalConnectionDTO) document.getBean();

		if (getExternalConnectionService().consultarConexoesAtivas(conexoesDTO)) {
			document.alert(UtilI18N.internacionaliza(request, "citcorpore.comum.registroJaCadastrado"));
			return;
		}

		if (conexoesDTO.getIdExternalConnection() == null || conexoesDTO.getIdExternalConnection() == 0) {
			getExternalConnectionService().create(conexoesDTO);
			document.alert(UtilI18N.internacionaliza(request, "MSG05"));
		} else {
			conexoesDTO.setDeleted(null);
			getExternalConnectionService().update(conexoesDTO);
			document.alert(UtilI18N.internacionaliza(request, "MSG06"));
		}

		HTMLForm form = document.getForm("form");
		form.clear();

		document.executeScript("limpar_LOOKUP_CONEXOES()");
		document.executeScript("fechaAlterarSenha()");
	}

	public void delete(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ExternalConnectionDTO conexoesDTO = (ExternalConnectionDTO) document.getBean();

		ImportarDadosService importarDadosService = (ImportarDadosService) ServiceLocator.getInstance().getService(ImportarDadosService.class, WebUtil.getUsuarioSistema(request));

		Collection<ImportarDadosDTO> importacoesRelacionadas = importarDadosService.consultarImportarDadosRelacionados(conexoesDTO.getIdExternalConnection());

		if (importacoesRelacionadas != null && !importacoesRelacionadas.isEmpty()) {

			document.alert(UtilI18N.internacionaliza(request, "MSG08"));
			return;

		}

		if (conexoesDTO.getIdExternalConnection().intValue() > 0) {
			if(getExternalConnectionService().deletarConexao(conexoesDTO)){
				document.alert(UtilI18N.internacionaliza(request, "MSG07"));
			} else {
				document.alert(UtilI18N.internacionaliza(request, "MSG10"));
				document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
				return;
			}
		}

		HTMLForm form = document.getForm("form");
		form.clear();

		document.executeScript("limpar_LOOKUP_CONEXOES();");
		document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
	}

	private Boolean testeConexaoComOsDadosInformados(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, ScriptException, Exception {
		ScriptEngineManager factory = new ScriptEngineManager();
		ScriptEngine engine = factory.getEngineByName("JavaScript");
		ExternalConnectionDTO obj = (ExternalConnectionDTO) document.getBean();
		Boolean aux = null;
		String url = obj.getUrlJdbc();
		if (obj.getJdbcDriver().indexOf("postgresql") >= 0) {
			url += obj.getJdbcDbName();
		}
		String conteudoScript = new String("function teste(){importPackage( java.sql );" + "var conn = DriverManager.getConnection( '" + url + "', '" + obj.getJdbcUser() + "', '" + obj.getJdbcPassword() + "' );" + "var stmt = conn.createStatement();" + "stmt.close();" + "conn.close();" + "return stmt;" + "}");

		engine.eval(conteudoScript);
		Invocable invocable = (Invocable) engine;

		try {
			invocable.invokeFunction("teste");
			aux = true;
		} catch (Exception e) {
			aux = false;
			e.printStackTrace();
		}
		return aux;

	}

	public void testeConexao(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, ScriptException, Exception {
		ExternalConnectionDTO obj = (ExternalConnectionDTO) document.getBean();

		if (obj.getUrlJdbc().equals("")) {
			document.alert(UtilI18N.internacionaliza(request, "externalconnection.obrigatorio.url"));
		} else {
			if (obj.getJdbcUser().equals("")) {
				document.alert(UtilI18N.internacionaliza(request, "externalconnection.obrigatorio.usuario"));
			} else {
				if (obj.getJdbcPassword().equals("")) {
					document.alert(UtilI18N.internacionaliza(request, "externalconnection.obrigatorio.senha"));
				} else {
					if (testeConexaoComOsDadosInformados(document, request, response)) {
						document.alert(UtilI18N.internacionaliza(request, "conexaoBI.testeConexaoSucesso"));
					} else {
						document.alert(UtilI18N.internacionaliza(request, "externalconnection.erro.conexao"));
					}
				}

			}
		}

	}

	private void inicializarCombo(HTMLSelect componenteCombo, HttpServletRequest request) {
		componenteCombo.removeAllOptions();
		componenteCombo.addOption("", UtilI18N.internacionaliza(request, "citcorpore.comum.selecione"));
		componenteCombo.addOption("J", UtilI18N.internacionaliza(request, "externalconnection.jdbc"));
	}

	public void restore(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ExternalConnectionDTO conexoesDTO = (ExternalConnectionDTO) document.getBean();
		conexoesDTO = (ExternalConnectionDTO) getExternalConnectionService().restore(conexoesDTO);
		HTMLForm form = document.getForm("form");
		form.clear();
		form.setValues(conexoesDTO);
	}

	private void carregaComboDriver(DocumentHTML document) throws Exception {
		HTMLSelect comboDriver = document.getSelectById("jdbcDriver");
		comboDriver.removeAllOptions();
		for (DriverJdbc driver : DriverJdbc.values()) {
			comboDriver.addOption(driver.getDriverName(), driver.getDatabaseName());
		}
	}

	private ExternalConnectionService getExternalConnectionService() throws ServiceException {
		if (externalConnectionService == null) {
			externalConnectionService = (ExternalConnectionService) ServiceLocator.getInstance().getService(ExternalConnectionService.class, null);
		}

		return externalConnectionService;
	}

}
