/*******************************************************************************
 * Copyright 2014 Centre for Development of Advanced Computing(C-DAC), Pune
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package in.cdac.medinfo.csnotk.csnolib.db;

import static in.cdac.medinfo.csnotk.csnolib.util.PropertyReader.loadSystemProperties;
import in.cdac.medinfo.csnotk.csnolib.commons.Constants;
import in.cdac.medinfo.csnotk.csnolib.util.PropertyReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
//Logs
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import in.cdac.medinfo.csnotk.csnolib.util.LoggerUtility;
/**
 * This class manages the database connection.
 */
public class ConnectionManager{
	private static final String jdbcClassName="org.h2.Driver";
	private static final String userName="csno";
	private static final String password="csno";
	private static Connection conn;
    private static final Logger logger = LogManager.getLogger(ConnectionManager.class);


	/**
	 * System properties loading
	 */
	static
	{
		conn=ConnectionManager.getConnection();
	}

	private ConnectionManager(){}


	/**
	 * returns singleton database connection object.
	 * @return instance of {@link Connection}.
	 */
	public static Connection getConnection(){
		if(conn!=null){
			try {
				if(conn.isClosed())
						conn=getConnectionInstance();
			}catch (SQLException e){
				//Log the Exception
				logger.error(LoggerUtility.Exception, "Connection object is already closed");
				logger.error(LoggerUtility.Exception, LoggerUtility.createErrorMessage(e));
			}
		}else
			conn=getConnectionInstance();
		return conn;
	}

	/**
	 * returns new database connection object.
	 * @return instance of {@link Connection}.
	 */
	private static Connection getConnectionInstance(){
		try{

			loadSystemProperties();
			Class.forName(jdbcClassName);
			conn = DriverManager.getConnection("jdbc:h2:"+PropertyReader.getProperty(Constants.DATA_DIR)+"/snomedct2;LOG=0;CACHE_SIZE=65536;LOCK_MODE=0;UNDO_LOG=0",userName,password);
			PropertyReader.getProperty(Constants.DATA_DIR);
		}catch (ClassNotFoundException | SQLException e){
			if(e instanceof SQLException){
				SQLException ex=(SQLException)e;
				logger.info(LoggerUtility.CONSOLE, "SQLException: {}" , ex.getMessage());
			    logger.info(LoggerUtility.CONSOLE, "SQLState: {}" , ex.getSQLState());
			    logger.info(LoggerUtility.CONSOLE, "VendorError: {}" , ex.getErrorCode());
			}
			//Log the Exception
			logger.error(LoggerUtility.Exception, LoggerUtility.createErrorMessage(e));
		}
		return conn;
	}
}
