package br.com.elotech.config;

import br.com.elotech.Main;
import br.com.elotech.model.ConnParams;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionUtil {
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    public static Connection getConnection() throws HibernateException, SQLException {
        Configuration cfg = getConfig();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
        return serviceRegistry.getService(ConnectionProvider.class).getConnection();
    }

    private static Configuration getConfig() {
        Properties prop = new Properties();
        ConnParams conn = Main.connParams;
        String driver = (conn.getDriver().equals("PDO_PGSQL") ? "org.postgresql.Driver" : "oracle.jdbc.driver.OracleDriver");
        String dialect = (conn.getDriver().equals("PDO_PGSQL") ? "org.hibernate.dialect.PostgreSQLDialect" : "org.hibernate.dialect.OracleDialect");
        String config = conn.getHost().concat(":").concat(conn.getPorta()).concat("/").concat(conn.getBanco());
        String url = (conn.getDriver().equals("PDO_PGSQL") ? "jdbc:postgresql://" : "jdbc:oracle:thin://");
        prop.setProperty("hibernate.connection.driver_class", driver);
        prop.setProperty("hibernate.connection.url", url.concat(config));
        prop.setProperty("hibernate.connection.username", conn.getUsername());
        prop.setProperty("hibernate.connection.password", conn.getPassword());
        prop.setProperty("hibernate.dialect", dialect);
        prop.setProperty("hibernate.hbm2ddl.auto", "validate");
        prop.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider");
        prop.setProperty("hibernate.current_session_context_class", "thread");

        prop.setProperty("hibernate.show_sql", "true");
        prop.setProperty("hibernate.format_sql", "true");
        prop.setProperty("hibernate.use_sql_comments", "true");

        Configuration cfg = new Configuration();
        cfg.setProperties(prop);
        return cfg;
    }
}
