package com.rjconsultores.ventaboletos.dao.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.logging.log4j.Logger;

import org.hibernate.SessionFactory;
import org.springframework.core.io.ClassPathResource;
import org.apache.logging.log4j.LogManager;

public class DBUtil {

	private static final Logger log = LogManager.getLogger(DBUtil.class);
	private static DBUtil INSTANCE;
	private static Properties p;
	private SessionFactory sessionFactory;

	public static DBUtil getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new DBUtil();
		}
		return INSTANCE;
	}

	private DBUtil() {
		p = new Properties();
		InputStream is;
		try {
			is = new ClassPathResource("/com/rjconsultores/ventaboletos/web/cliente/conf/database.properties").getInputStream();

			p.load(is);
			is.close();
		} catch (IOException e) {
			log.error("Erro ao carregar o properties do banco de dados", e);
		}
	}

	public boolean isOracle() {
		return p.getProperty("database.dialect").toUpperCase().contains("ORACLE");
	}

	public boolean isSQLServer() {
		return p.getProperty("database.dialect").toUpperCase().contains("SQLSERVER");
	}

	public boolean isRDS() {
		return Boolean.valueOf(p.getProperty("database.rds", "false"));
	}

	public String dbSysdate() {
		if (isOracle()) {
			if (isRDS()) {
				return "DATETIME_RDS()";
			} else {
				return "SYSDATE";
			}
		}
		if (isSQLServer()) {
			return "GETDATE()";
		}
		return "";
	}
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	// private String getDefaultSchema(){
	// return p.getProperty("database.default_schema").toUpperCase();
	// }

	// public String agregarDefaulSchema(String objBaseDados){
	// String [] array = objBaseDados.split("\\.");
	//
	// if (array.length == 1){
	// return getDefaultSchema() + "." + array[0];
	// }else if (array.length == 2){
	// return getDefaultSchema() + "." + array[1];
	// }
	// return objBaseDados;
	// }
}
