package br.com.centralit.citcorpore.negocio;

import java.io.File;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import br.com.centralit.citcorpore.bean.AtributoDemandaDTO;
import br.com.centralit.citcorpore.integracao.AtributoDemandaDao;
import br.com.citframework.dto.IDto;
import br.com.citframework.excecao.LogicException;
import br.com.citframework.excecao.ServiceException;
import br.com.citframework.service.CrudServiceImpl;
import br.com.citframework.service.ServiceLocator;
import br.com.citframework.util.UtilDatas;
import br.com.citframework.util.UtilI18N;

@SuppressWarnings("unchecked")
public class AtributoDemandaServiceEjb extends CrudServiceImpl implements AtributoDemandaService {

	private ImportarDadosArquivoService importarDadosArquivoService;
	
	@Override
	protected AtributoDemandaDao getDao() {
		return new AtributoDemandaDao();
	}
	
	private ImportarDadosArquivoService getImportarDadosArquivoService() throws ServiceException{
		if(importarDadosArquivoService == null)
			importarDadosArquivoService = (ImportarDadosArquivoService) ServiceLocator.getInstance().getService(ImportarDadosArquivoService.class, null);
		return importarDadosArquivoService;
	}
	
	@Override
	public String importarDados(File carga, HttpServletRequest request) throws Exception {
		Map<String, String> mapDados = getImportarDadosArquivoService().getMapaDados(carga);
		if(mapDados == null || mapDados.isEmpty())
			return "importaratributofinanceiro.falhaimportacao";
		for(String key : mapDados.keySet()){
			try{
				AtributoDemandaDTO atributoDemandaDTO = new AtributoDemandaDTO();
				if(!key.isEmpty() && mapDados.get(key) != null && !mapDados.get(key).isEmpty()
						&& (!mapDados.get(key).equals(UtilI18N.internacionaliza(request, "importaratributosfinanceiros.valor")) && !key.equals(UtilI18N.internacionaliza(request, "importaratributosfinanceiros.nomeAtributo")))){
					atributoDemandaDTO.setNome(key);
					atributoDemandaDTO.setValor(mapDados.get(key));
					this.create(atributoDemandaDTO);
				}
			} catch (Exception e){e.printStackTrace();}
		}
		return "importaratributofinanceiro.sucesso";
	}

	@Override
	public void delete(IDto model) throws ServiceException, LogicException {
		AtributoDemandaDTO atributoDemandaDTO = (AtributoDemandaDTO) this.restore(model);
		atributoDemandaDTO.setDataHoraFim(UtilDatas.getDataHoraAtual());
		this.update(atributoDemandaDTO);
	}
	
}
