/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.cayenne.access.DataDomain;
import org.apache.cayenne.access.DataNode;
import org.apache.cayenne.conf.DefaultConfiguration;
import org.apache.cayenne.conn.DriverDataSource;
import org.apache.cayenne.dba.AutoAdapter;
import org.apache.cayenne.map.DataMap;

import com.evolute.utils.Singleton;

import com.evolute.utils.error.ErrorLogger;
import siprp.SingletonConstants;

/**
 *
 * @author lluis
 */
public class DblocalRelatorios {
    //String connectionURL = "jdbc:postgresql://storage/siprp_local"; //testes

    //String connectionURL = "jdbc:postgresql://storage/siprp_local_3"; //testes local_3
    String connectionURL = "jdbc:postgresql://localhost:5436/siprp_local_3";



    String User = "postgres";
    String Pass = null;
    Connection connection = null;

    public Connection connect() throws Exception
    {
        Class.forName("org.postgresql.Driver").newInstance();
            connection = DriverManager.getConnection(connectionURL, User, Pass);

        DataDomain domain = DefaultConfiguration.getSharedConfiguration().getDomain();
		DataMap map = domain.getMap( "SIPRPMap" );
		DriverDataSource dataSource = new DriverDataSource((String) Singleton.getInstance( SingletonConstants.LOCAL_DRIVER_NAME ), connectionURL, User, Pass );
		DataNode node = new DataNode("SIPRPNode");
		node.setDataSource( dataSource );
		node.setAdapter( new AutoAdapter(dataSource) );
		node.addDataMap( map );
		node.setEntityResolver( domain.getEntityResolver() );
		domain.reset();
		domain.addNode( node );

        //HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        //session.setAttribute("connection_local", connection);
        return connection;
    }

    public Statement createStatement()
    {
        //HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        //connection = (Connection) session.getAttribute("connection_local");

        Statement st;
        try
        {
            st = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            return st;
        }
        catch(Exception ex)
        {
            ErrorLogger.logException( ex );
            return null;
        }
    }

    public void close() throws Exception
    {
        connection.close();
    }

}
