package workhourscontrol.client.service;

import java.io.File;
import java.util.List;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import workhourscontrol.client.ConfiguracoesAplicacao;
import workhourscontrol.client.MainApp;
import workhourscontrol.entity.RegistroHora;
import workhourscontrol.exception.ControleHorasException;
import workhourscontrol.service.ControleHoras;
import workhourscontrol.service.ControleHorasHttp;
import workhourscontrol.service.ControleHorasHttpBuilder;
import workhourscontrol.service.ControleHorasPlanilha;
import workhourscontrol.service.ControleHorasPlanilhaBuilder;

/**
 * Servio responsvel por fazer o lanamento das horas
 */
public class IntegracaoService {

	private static Logger logger = Logger.getLogger(IntegracaoService.class);

	private static IntegracaoService integracaoService;

	private ConfiguracoesAplicacao configuracaoAplicacao;

	private ControleHoras controleHorasHttp;

	/** Singleton */
	public static IntegracaoService getInstance() {
		if (Objects.isNull(integracaoService)) {
			integracaoService = new IntegracaoService();
			integracaoService.configuracaoAplicacao = MainApp.configuracoesAplicacao;
			integracaoService.buildControleHorasHttp();
		}
		return integracaoService;
	}

	private void buildControleHorasHttp() {

		try {

			if (Objects.isNull(controleHorasHttp)) {

				ControleHorasHttpBuilder builder = new ControleHorasHttpBuilder(getControleHorasImpl());

				controleHorasHttp = builder.setProxy(configuracaoAplicacao.getProxyHost(),Integer.parseInt(configuracaoAplicacao.getProxyPort()))
						.setCredenciaisProxy(configuracaoAplicacao.getProxyUser(),configuracaoAplicacao.getProxyPassword())
						.setCredenciaisAcessoRemoto(configuracaoAplicacao.getLoginAplicacao(), configuracaoAplicacao.getPasswordAplicacao())
						.build();
			}
		} catch(Exception e) {
			logger.warn("Ocorreu um erro ao construir componente para integrao, a integrao no ser realizada", e);
		}

	}

	/**
	 * Aponta horas em sistema de acordo com implementao de ControleHorasHttp
	 * @param registros
	 */
	public void sincronizarRegistrosHora(List<RegistroHora> registros) {
		try {
			controleHorasHttp.registrarHoras(registros);
			controleHorasHttp.fecharConexao();
		} catch (ControleHorasException e) {
			logger.error("Erro ao sincronizar registros.", e);
		}

	}

	public double obterSaldoHoras() {
		try {
			double result = controleHorasHttp.obterSaldoHoras();
			controleHorasHttp.fecharConexao();
			return result;
		} catch (ControleHorasException e) {
			logger.error("Erro ao obter saldo de horas.", e);
		}
		return 0;
	}


	/**
	 * Aponta horas em planilha de acordo com implementao de ControleHoraPlanilha
	 */
	public void sincronizarRegistrosHoraComPlanilha(List<RegistroHora> registros, File arquivo) {
		try {
			ControleHorasPlanilhaBuilder builder = new ControleHorasPlanilhaBuilder(new ControleHorasPlanilha());
			builder.setPlanilha(arquivo);
			ControleHoras controleHorasPlanilha = builder.build();
			controleHorasPlanilha.registrarHoras(registros);
			controleHorasPlanilha.fecharConexao();
		} catch (ControleHorasException e) {
			logger.error("Erro ao sincronizar registros com planilha.", e);
		}
	}


	/**
	 * Instancia implementao de Controle Horas
	 * @return
	 * @throws Exception
	 */
	private ControleHorasHttp getControleHorasImpl() throws Exception {
		final String className = configuracaoAplicacao.getControleHorasClass();
		try {
			if (StringUtils.isBlank(className)) {
				final String msg = "Propriedade controleHorasClass no encontrada";
				logger.warn(msg);
				throw new Exception(msg);
			}

			return (ControleHorasHttp) Class.forName(className).newInstance();

		} catch (InstantiationException | IllegalAccessException e) {
			logger.error("Ocorreu um erro ao instanciar " + className, e);
			throw new RuntimeException(e);

		} catch (ClassNotFoundException e) {
			logger.error("Classe " + className + " no encontrada.", e);
			throw new RuntimeException(e);
		}
	}
}

@@ -2247,46 +2247,8 @@
 s);%0A
-%09%09%09controleHorasHttp.fecharConexao();%0A
 %09%09%7D 
@@ -2274,32 +2274,32 @@
 sException e) %7B%0A
+
 %09%09%09logger.error(
@@ -2335,24 +2335,76 @@
 s.%22, e);%0A%09%09%7D
+ finally %7B%0A%09%09%09controleHorasHttp.fecharConexao();%0A%09%09%7D
 %0A%0A%09%7D%0A%0A%09publi
@@ -2500,46 +2500,8 @@
 ();%0A
-%09%09%09controleHorasHttp.fecharConexao();%0A
 %09%09%09r
@@ -2545,32 +2545,32 @@
 sException e) %7B%0A
-
 %09%09%09logger.error(
@@ -2602,24 +2602,76 @@
 oras.%22, e);%0A
+%09%09%7D finally %7B%0A%09%09%09controleHorasHttp.fecharConexao();%0A
 %09%09%7D%0A%09%09return

Ajuste em fechamento de conexão.