package br.com.centralit.inventory;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;

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

import br.com.centralit.citcorpore.bean.StatusInventarioDTO;
import br.com.centralit.citcorpore.metainfo.util.JSONConverter;
import br.com.centralit.citcorpore.negocio.StatusInventarioService;
import br.com.centralit.citcorpore.util.Enumerados.StatusInventario;
import br.com.centralit.citsmart.rest.schema.CtInventario;
import br.com.centralit.citsmart.rest.schema.HostItem;
import br.com.centralit.mongodb.MongoConsumer;
import br.com.citframework.excecao.ServiceException;
import br.com.citframework.service.ServiceLocator;

public class InventoryConsumer implements MongoConsumer {
	private ICitGerenteInventory citGerenteInventory;
	private StatusInventarioService statusInventarioService;

	private static final Logger LOGGER = Logger.getLogger(InventoryConsumer.class);

	@Override
	public void read(final String message) {
		LOGGER.debug("Citsmart ITSM > Nova mensagem recebida do Citsmart Inventory.");

		try {
			JSONObject object = new JSONObject(message);

			if (object != null) {
				CtInventario ctInventario = JSONConverter.fromJson(object.toString(), CtInventario.class);

				StatusInventarioDTO statusInventarioDTO = getStatusInventario(ctInventario);

				Collection<StatusInventarioDTO> colStatusInventarioDTO = new ArrayList<>();
				if (statusInventarioDTO.getIdentificacao() != null && !statusInventarioDTO.getIdentificacao().isEmpty()) {
					colStatusInventarioDTO = getStatusInventarioService().findByIdentificacao(statusInventarioDTO.getIdentificacao());
				}

				if ((colStatusInventarioDTO == null || colStatusInventarioDTO.isEmpty()) && statusInventarioDTO.getIp() != null && !statusInventarioDTO.getIp().isEmpty()) {
					colStatusInventarioDTO = getStatusInventarioService().findByIp(statusInventarioDTO.getIp());
				}

				if (colStatusInventarioDTO != null && !colStatusInventarioDTO.isEmpty()) {
					statusInventarioDTO.setIdStatusInventario(colStatusInventarioDTO.iterator().next().getIdStatusInventario());
					getStatusInventarioService().update(statusInventarioDTO);
				} else {
					getStatusInventarioService().create(statusInventarioDTO);

				}

				if (StatusInventario.INVENTARIADA.getId().equals(statusInventarioDTO.getIdStatus())) {
					getCitGerenteInventory().processaInventory(ctInventario);
				}

				LOGGER.debug("Citsmart ITSM > Mensagem processada com sucesso.");
			} else {
				LOGGER.error(String.format("Citsmart ITSM > Mensagem inválida."));
			}
		} catch (final Exception ex) {
			LOGGER.error(String.format("Citsmart ITSM > Erro ao processar mensagem. Mensagem: %s.", ex.getMessage() != null ? ex.getMessage() : "Nao informada"), ex);
		}
	}

	public StatusInventarioDTO getStatusInventario(CtInventario inventario) {
		StatusInventarioDTO statusInventarioDTO = new StatusInventarioDTO();

		for (HostItem hostItem : inventario.getInventario()) {
			if (hostItem.getName().equalsIgnoreCase("HARDWARE")) {
				try {
					if (hostItem.getProperties().get("NAME") != null && !hostItem.getProperties().get("NAME").isEmpty()) {
						statusInventarioDTO.setIdentificacao(hostItem.getProperties().get("NAME"));
					}

					if (hostItem.getProperties().get("IPCONF") != null && !hostItem.getProperties().get("IPCONF").isEmpty()) {
						statusInventarioDTO.setIp(hostItem.getProperties().get("IPCONF"));
					} else if (hostItem.getProperties().get("IPADDR") != null && !hostItem.getProperties().get("IPADDR").isEmpty()) {
						statusInventarioDTO.setIp(hostItem.getProperties().get("IPADDR"));
					}

					if (hostItem.getProperties().get("IDSTATUS") != null && !hostItem.getProperties().get("IDSTATUS").isEmpty()) {
						statusInventarioDTO.setIdStatus(Integer.parseInt(hostItem.getProperties().get("IDSTATUS")));
					}

					if (hostItem.getProperties().get("DTTIME") != null && !hostItem.getProperties().get("DTTIME").isEmpty()) {
						statusInventarioDTO.setDataHora(new Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(hostItem.getProperties().get("DTTIME")).getTime()));
					}

					if (hostItem.getProperties().get("IDCON") != null && !hostItem.getProperties().get("IDCON").isEmpty()) {
						statusInventarioDTO.setIdConexao(Integer.parseInt(hostItem.getProperties().get("IDCON")));
					}
				} catch (ParseException e) {
				}
			}
		}

		return statusInventarioDTO;
	}

	/**
	 * Retorna uma instância do CitGerenteInventory.
	 *
	 * @return ICitGerenteInventory
	 * @author rodrigo.acorse
	 */
	private ICitGerenteInventory getCitGerenteInventory() {
		if (citGerenteInventory == null) {
			return new CitGerenteInventory();
		}
		return citGerenteInventory;
	}

	public StatusInventarioService getStatusInventarioService() throws ServiceException, Exception {
		if (statusInventarioService == null) {
			statusInventarioService = (StatusInventarioService) ServiceLocator.getInstance().getService(StatusInventarioService.class, null);
		}

		return statusInventarioService;
	}
}
