package br.com.centralit.citcorpore.negocio;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collection;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import br.com.centralit.citcorpore.bean.EvmConexaoDTO;
import br.com.centralit.citcorpore.bean.EvmInventoryConfiguracaoDTO;
import br.com.centralit.citcorpore.bean.StatusInventarioDTO;
import br.com.centralit.citcorpore.integracao.StatusInventarioDAO;
import br.com.centralit.citcorpore.util.IPInventario;
import br.com.citframework.excecao.PersistenceException;
import br.com.citframework.service.CrudServiceImpl;

public class StatusInventarioServiceEjb extends CrudServiceImpl implements StatusInventarioService {

	private static final Logger LOGGER = Logger.getLogger(StatusInventarioServiceEjb.class);
	private StatusInventarioDAO dao;

	@Override
	protected StatusInventarioDAO getDao() {
		if (dao == null) {
			dao = new StatusInventarioDAO();
		}
		return dao;
	}

	@Override
	public Collection<StatusInventarioDTO> list(Integer idConexao, String identificacao, String ip, Integer idStatus, Integer quantidadeAtual, Integer quantidadeCarregar) throws PersistenceException {
		return getDao().list(idConexao, identificacao, ip, idStatus, quantidadeAtual, quantidadeCarregar);
	}

	@Override
	public Collection<StatusInventarioDTO> findByIdentificacao(String identificacao) throws Exception {
		return getDao().findByIdentificacao(identificacao);
	}

	@Override
	public Collection<StatusInventarioDTO> findByIp(String ip) throws Exception {
		return getDao().findByIp(ip);
	}

	@Override
	public boolean realizaInventarioIp(EvmInventoryConfiguracaoDTO evmInventoryConfiguracaoDTO, EvmConexaoDTO evmConexaoDTO) {
		try {
			LOGGER.info("Citsmart > Solicitando inventario ao Citsmart Inventory.");

			// TODO Adicionar método de autenticação na conexão
			// final String userName = evmGerenteDTO.getEvmConexaoDto().getUsuario();
			// final String password = evmGerenteDTO.getEvmConexaoDto().getSenha();
			//
			String userPassword = "ADMIN:1";
			String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());

			/**
			 * Conectando ao Citsmart Monitor
			 */
			final URL url = new URL(IPInventario.montaUrlWs(evmConexaoDTO, evmInventoryConfiguracaoDTO, "obterInventario"));
			final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("Authorization", "Basic " + encoding);
			connection.setRequestMethod("PUT");
			connection.setRequestProperty("Content-Type", "application/json");

			connection.setDoOutput(true);
			connection.setInstanceFollowRedirects(false);

			String dados = new JSONObject()
					.put("faixa", evmInventoryConfiguracaoDTO.getFaixaIp())
					.put("completo", "false")
					.put("destinoParaEVM", "false")
					.put("portaAgenteDotNet", evmInventoryConfiguracaoDTO.getPortaNet())
					.put("portaSNMP", evmInventoryConfiguracaoDTO.getPortaSNMP())
					.put("destino", evmInventoryConfiguracaoDTO.getDestinoInventario())
					.put("idConexao", evmInventoryConfiguracaoDTO.getIdConexao())
					.toString();

			try (final OutputStream os = connection.getOutputStream()) {
				os.write(dados.getBytes());
				os.flush();
			}

			LOGGER.info(String.format("Citsmart > ReponseCode: %s. ResponseMessage: %s", connection.getResponseCode(), connection.getResponseMessage()));

			connection.disconnect();

			return true;
		} catch (final Exception e) {
			LOGGER.warn(String.format("Citsmart > Nao foi possivel realizar a conexao com o Citsmart Inventory. Mensagem: %s.", (e.getMessage() != null ? e.getMessage() : "Nao informada")));
		}

		return false;
	}
}
