load('/rules/notaEntrada/validaDados.js');
load('/rules/notaSaida/validaDados.js');
load('/service/notaFiscal/NotaFiscalEntradaService.js');
load('/service/notaFiscal/NotaFiscalSaidaService.js');

var i = JavaImporter( // importando pacote do java
    Packages.java.io,
    Packages.java.lang
);

NotaFiscalService = function() {

}

NotaFiscalService.prototype.notaSaida = function(mapper, json) {
    var notaSaida = new NotaSaida();

    var resultValidacao = notaSaida.validaDadosNotaSaida(json);

    if(! resultValidacao.error){
        var nfSaida = new NotaFiscalSaida();
         return nfSaida.save(mapper, resultValidacao);
    }else{
       return resultValidacao;
    }

}

NotaFiscalService.prototype.notaEntrada = function(mapper, json) {
    var notaEntrada = new NotaEntrada();

    var resultValidacao = notaEntrada.validaDadosNotaEntrada(json);

    if(! resultValidacao.error){
        var nfEntrada = new NotaFiscalEntrada();
         return nfEntrada.save(mapper, resultValidacao);
    }else{
       return resultValidacao;
    }
}

NotaFiscalService.prototype.isJavaObject = function(obj) {
    return obj instanceof java.lang.Object;
}

NotaFiscalService.prototype.save = function(notaFiscal) {

    with(i) {
        var mapper = null;
        try {

            notaFiscal.cdNf = 0; //Removendo codigo da notaFiscal caso seja enviado anteriormente

            if (notaFiscal.tpNf == 0) {
				
				mapper = mapperFactory.createMapperMult(["Importador", "EstNfEnt", "EstNfEntIt", "GlbMovOp", "EstNfEntDanfeProvisorio", "EstNfEntRcCli", "EstNfEntPgForn", "EstNfEntPrcFilial", "EstNfEntDanfeProvisorioEstNfEnt", "EstNfSerie", "EstNfEntDanfeProvisorioNaoEncontrado", "EstNfEntPedCp", "EstPedCp", "EstProdCpl", "RcCli", "EstProdEntGrpEcon", "EstProdEntGrpEconEstNfEntIt"]);
  
                var returnoNota = this.notaEntrada(mapper, notaFiscal);

                if(returnoNota.error){
                    throw returnoNota;
                }
                
            } else {
                mapper = mapperFactory.createMapperMult(
				["EfNfCtrNr", "EstNfSai", "EstNfSaiIt", "EstNfSaiPrcFilial", "EstNfSaiNfe", "EstNfSaiRcCli", 
				 "EstNfSaiPgForn", "EstProdTransfConf", "EstProdTransfConfFases", "EstProdTransfConfFasesItens", 
				 "EstProdTransf", "EstProdTransfIt", "EstNfSaiPedVd", "EstPedVd", "EstPedVdIt", "EstProdCpl", 
                 "EstNfSaiVendas", "EstProdTransfPedVd", "PrcFilialRcCli", "PgFornRcCli", "RcCli"]);
                 
                notaFiscal.nrNf = (notaFiscal.nrNf ? notaFiscal.nrNf : notaFiscal.nfNf);
                var returnoNota = this.notaSaida(mapper, notaFiscal);

                if(returnoNota.error){
                    throw returnoNota;
                }
            }
            mapper.commit();

            return {error : false};

        } catch (err) {

			if(mapper !== null){
				mapper.rollback();
			}
			
			var erroResult = this.extractError(err);

            if(erroResult && erroResult.includes('Violation of PRIMARY KEY constraint'))
                throw erroResult;

            if(notaFiscal){
                var objectMapper = new com.google.gson.GsonBuilder().create();
                
                var mapperErro = mapperFactory.createMapperMult(["AdmErroEstNfIntegracoes"]);
                var msgErro = {};

                msgErro.nrNf = notaFiscal.nrNf;
                msgErro.dtEmiNf = notaFiscal.dtEmiNf;
                msgErro.cdForn = notaFiscal.cdForn || 0;
                msgErro.serieNf = notaFiscal.cdNfSerie;
                msgErro.tpTransa = notaFiscal.tpNf;
                msgErro.cnpjForn = notaFiscal.cnpjEmitente || '';
                msgErro.nrAutorizador = notaFiscal.nrAut || '';
                msgErro.jsonEnviado = objectMapper.toJson(notaFiscal);
                msgErro.stsErro = 2; // Erro
                msgErro.cdUsuCorrecao = 0;
                msgErro.laudo = erroResult;
                
                try {
                    mapperErro.insert("AdmErroEstNfIntegracoes.incluirAdmErroEstNfIntegracoes", msgErro);
     
                    mapperErro.commit();
                } catch (err1) {
                    println('NotaFiscalService.prototype.save catch (err1) ' + err1);
                    mapperErro.rollback();
                    
                    if(this.isJavaObject(err1)){
    					var objectMapper = new com.google.gson.GsonBuilder().create();
                        erroResult = objectMapper.toJson(err1);
                    }else{
                        erroResult = JSON.stringify(err1);
                    }
                    
                    throw errorMessage1;
                } finally {
                    mapperErro.close();
                }
            }
            
            return {error : true, message : "Erro armazendo em adm erro"};
        } finally {
			if(mapper !== null){
				mapper.close();
			}
        }
    }
}

NotaFiscalService.prototype.extractError = function(err){
    var objectMapper = new com.google.gson.GsonBuilder().create();
    var erroResult = "";
    
    if(err.javaException 
		&& err.javaException instanceof org.apache.ibatis.exceptions.PersistenceException
		&& err.javaException.cause)
	{
		erroResult = objectMapper.toJson({message : err.javaException.cause.message.replaceAll("\"", "\\\"")});   
    }else{
		if(err.javaException)
		{
			erroResult = objectMapper.toJson({message : err.javaException.message.replaceAll("\"", "\\\"")});
		}else{
			erroResult = objectMapper.toJson(err);
		}
	}
	
	return erroResult;

}