package br.com.centralit.citcorpore.integracao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import br.com.centralit.citcorpore.bean.ExternalConnectionDTO;
import br.com.centralit.citcorpore.util.CITCorporeUtil;
import br.com.citframework.excecao.PersistenceException;
import br.com.citframework.integracao.Condition;
import br.com.citframework.integracao.CrudDaoDefaultImpl;
import br.com.citframework.integracao.Field;
import br.com.citframework.integracao.Order;
import br.com.citframework.integracao.core.SequenceBlockCache;
import br.com.citframework.integracao.core.SequenceBlockPool;
import br.com.citframework.util.Constantes;
import br.com.citframework.util.DBItemConvertion;
import br.com.citframework.util.XmlReadDBItemConvertion;

public class ExternalConnectionDao extends CrudDaoDefaultImpl {
	private static volatile SequenceBlockCache globalCache = null;

	public ExternalConnectionDao() {
		super(Constantes.getValue("DATABASE_ALIAS"), null);
		globalCache = SequenceBlockPool.getFromPool(Constantes.getValue("DATABASE_ALIAS"));
	}

	@Override
	public Collection<Field> getFields() {
		Collection<Field> listFields = new ArrayList<>();
		listFields.add(new Field("idexternalconnection" ,"idExternalConnection", true, true, false, false));
		listFields.add(new Field("nome" ,"nome", false, false, false, false));
		listFields.add(new Field("tipo" ,"tipo", false, false, false, false));
		listFields.add(new Field("urljdbc" ,"urlJdbc", false, false, false, false));
		listFields.add(new Field("jdbcdbname" ,"jdbcDbName", false, false, false, false));
		listFields.add(new Field("jdbcdriver" ,"jdbcDriver", false, false, false, false));
		listFields.add(new Field("jdbcuser" ,"jdbcUser", false, false, false, false));
		listFields.add(new Field("jdbcpassword" ,"jdbcPassword", false, false, false, false));
		listFields.add(new Field("filename" ,"fileName", false, false, false, false));
		listFields.add(new Field("schemadb" ,"schemaDb", false, false, false, false));
		listFields.add(new Field("deleted", "deleted", false, false, false, false));
		return listFields;
	}

	@Override
	public String getTableName() {
		return this.getOwner() + "ExternalConnection";
	}

	@Override
	@SuppressWarnings("unchecked")
	public Collection<ExternalConnectionDTO> list() throws PersistenceException {
		List<Order> list = new ArrayList<Order>();
		list.add(new Order("nome"));
		return super.list(list);
	}

	@Override
	public Class<ExternalConnectionDTO> getBean() {
		return ExternalConnectionDTO.class;
	}

	public Integer getNextKey(String nomeTabela, String nomeCampo) throws PersistenceException {
		try {
			final Long r = globalCache.getNextId(getRealName(nomeTabela), getRealName(nomeCampo));
			return r.intValue();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	public static String getRealName(String nome) throws Exception {
		final XmlReadDBItemConvertion xmlReadDB = XmlReadDBItemConvertion.getInstance(CITCorporeUtil.SGBD_PRINCIPAL);
		if (xmlReadDB != null) {
			final Collection<DBItemConvertion> col = xmlReadDB.getItens();
			if (col != null && col.size() > 0) {
				for (final Iterator<DBItemConvertion> it = col.iterator(); it.hasNext();) {
					final DBItemConvertion dbItemConvertion = it.next();

					if (nome != null && dbItemConvertion != null && nome.equalsIgnoreCase(dbItemConvertion.getNameToBeConverted())) {
						nome = dbItemConvertion.getNameAfterConversion();
						break;
					}
				}
			}
		}

		return nome;
	}

	public void executeSQLUpdate(String sql, Object[] objs) throws PersistenceException{
		this.execUpdate(sql, objs);
	}

	public boolean consultarConexoesAtivas(ExternalConnectionDTO obj) throws PersistenceException {
		List<String> parametro = new ArrayList<String>();
		List<?> list = new ArrayList<>();
		String sql = "select idexternalconnection From " + getTableName() + "  where  nome = ?   and deleted is null ";

		if(obj.getIdExternalConnection() != null){
			sql+=" and idexternalconnection <> "+ obj.getIdExternalConnection();
		}

		parametro.add(obj.getNome());
		list = this.execSQL(sql, parametro.toArray());
		if (list != null && !list.isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	public boolean validaInsert(ExternalConnectionDTO obj){
		return false;
	}

	@SuppressWarnings("unchecked")
	public Collection<ExternalConnectionDTO> findByNome(ExternalConnectionDTO conexoesDTO) throws PersistenceException {
		List<Condition> condicao = new ArrayList<Condition>();
		List<Order> ordenacao = new ArrayList<Order>();

		condicao.add(new Condition("nome", conexoesDTO.getNome()));
		condicao.add(new Condition(Condition.AND, "deleted", Condition.IS, null));

		ordenacao.add(new Order("nome"));

		return super.findByCondition(condicao, ordenacao);
	}

	@SuppressWarnings("unchecked")
	public Collection<ExternalConnectionDTO>  seConexaoJaCadastrada(ExternalConnectionDTO conexoesDTO) throws PersistenceException {
		List<String> parametro = new ArrayList<String>();
		List<?> list = new ArrayList<Object>();
		String sql = "";
		sql = " select lower(nome) from externalconnection where nome = lower(?) ";

		parametro.add(conexoesDTO.getNome().trim().toLowerCase());
		list = this.execSQL(sql, parametro.toArray());
		return (Collection<ExternalConnectionDTO>) list;
	}

	@SuppressWarnings("unchecked")
	public Collection<ExternalConnectionDTO> listarAtivas() throws PersistenceException {
		List<Condition> condicao = new ArrayList<Condition>();
		List<Order> ordenacao = new ArrayList<Order>();

		ordenacao.add(new Order("nome"));
		condicao.add(new Condition("deleted", Condition.IS, null));
		return super.findByCondition(condicao, ordenacao);
	}
}
