package br.com.centralit.inventory;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

import br.com.centralit.citcorpore.bean.FormulaDTO;
import br.com.centralit.citcorpore.bean.ItemConfiguracaoDTO;
import br.com.centralit.citcorpore.comm.server.ProcessarHashmapInventarioAgente;
import br.com.centralit.citcorpore.metainfo.script.ScriptRhinoJSExecute;
import br.com.centralit.citcorpore.metainfo.util.RuntimeScript;
import br.com.centralit.citcorpore.negocio.FormulaService;
import br.com.centralit.citcorpore.negocio.ItemConfiguracaoService;
import br.com.centralit.citsmart.rest.schema.CtInventario;
import br.com.centralit.citsmart.rest.schema.HostItem;
import br.com.citframework.excecao.LogicException;
import br.com.citframework.excecao.ServiceException;
import br.com.citframework.service.ServiceLocator;
import br.com.citframework.util.UtilDatas;

/**
 * Gerencia as ações executadas para as ocorrências.
 * 
 * @author rodrigo.acorse
 *
 */
@SuppressWarnings("unchecked")
public class CitGerenteInventory implements ICitGerenteInventory {

	private static final Logger logger = Logger.getLogger(CitGerenteInventory.class);

	private ItemConfiguracaoService itemConfiguracaoService;
	private FormulaService formulaService;

	/**
	 * Processa o inventário recebido por mensagem.
	 * 
	 * @param CtInventario
	 * @author rodrigo.acorse
	 * @throws Exception
	 */
	@Override
	public void processaInventory(CtInventario ctInventario) throws Exception {
		try {
			if (ctInventario.getInventario() != null && !ctInventario.getInventario().isEmpty()) {
				persistirIC(ctInventario.getInventario());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void persistirIC(Set<HostItem> objetosInventario) throws ServiceException, LogicException, Exception {
		ProcessarHashmapInventarioAgente mapReadDtdAgente = new ProcessarHashmapInventarioAgente();

		List<ItemConfiguracaoDTO> list = mapReadDtdAgente.processarHashmapInventario(objetosInventario);

		SimpleDateFormat spd = new SimpleDateFormat("yyyyMMdd");
		Date dataAtual = UtilDatas.getDataAtual();
		String dataAtualInv = spd.format(dataAtual).trim();

		if (list != null) {
			try {
				Collection<FormulaDTO> col = getFormulaService().findByIdentificador(FormulaDTO.FORMULA_INVENTORY_PROCESS_SAVE);
				if (col != null && !col.isEmpty()) {
					for (FormulaDTO formulaDTO : col) {
						if (formulaDTO != null) {
							String strScript = formulaDTO.getConteudo();
							if (strScript != null && !strScript.trim().equalsIgnoreCase("")) {
								ScriptRhinoJSExecute scriptExecute = new ScriptRhinoJSExecute();
								RuntimeScript runtimeScript = new RuntimeScript();
								Context cx = Context.enter();
								Scriptable scope = cx.initStandardObjects();
								scope.put("listaInfo", scope, list);
								// scope.put("fileName", scope, fileName);
								// scope.put("netMapDTO", scope, netMapDTO);
								scope.put("thread", scope, this);
								scope.put("out", scope, System.out);
								scope.put("dataAtualInv", scope, dataAtualInv);
								scope.put("RuntimeScript", scope, runtimeScript);
								scriptExecute.processScript(cx, scope, strScript, FormulaDTO.FORMULA_INVENTORY_PROCESS_SAVE);
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				List<ItemConfiguracaoDTO> listaSincronizada = Collections.synchronizedList(new ArrayList<ItemConfiguracaoDTO>(list));
				synchronized (listaSincronizada) {
					if (listaSincronizada != null && !listaSincronizada.isEmpty()) {
						for (ItemConfiguracaoDTO itemConfiguracaoDTO : listaSincronizada) {
							getItemConfiguracaoService().createItemConfiguracao(itemConfiguracaoDTO, null);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public ItemConfiguracaoService getItemConfiguracaoService() throws ServiceException, Exception {
		if (itemConfiguracaoService == null) {
			itemConfiguracaoService = (ItemConfiguracaoService) ServiceLocator.getInstance().getService(ItemConfiguracaoService.class, null);
		}

		return itemConfiguracaoService;
	}

	public FormulaService getFormulaService() throws ServiceException, Exception {
		if (formulaService == null) {
			formulaService = (FormulaService) ServiceLocator.getInstance().getService(FormulaService.class, null);
		}

		return formulaService;
	}

}
