/*******************************************************************************
 * Copyright 2016 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.icdmap;

import static in.cdac.medinfo.csnotk.csnolib.util.PropertyReader.getProperty;
import static in.cdac.medinfo.csnotk.csnolib.util.PropertyReader.loadSystemProperties;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

//Logs
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import in.cdac.medinfo.csnotk.csnolib.util.LoggerUtility;

/**
 * Establishes connection to ICD database (if any) and to get ICD-10 term for the provided ICD-10 code.
 */
class ICDDBManager {

	private static Connection conn;
	private static Statement stmt;
	private static URL jarURL;
	private static boolean ICDDBStatus = false;

	public static void setupICDDB()
	{
        Logger logger = LogManager.getLogger(ICDDBManager.class);
		try {
			loadSystemProperties();
			File jarFile = null;
			jarFile = new File(ICDDBManager.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());


			jarURL = new URL("jar:file:"+jarFile.getParentFile().getPath()+File.separator+getProperty(queryConstants.ICDJARNAME) + ".jar!/");

			String classname = getProperty(queryConstants.ICDDRIVERNAME);
			URLClassLoader ucl = new URLClassLoader(new URL[] { jarURL });
			Driver d = (Driver)Class.forName(classname, true, ucl).newInstance();
			DriverManager.registerDriver(new DriverWrap(d));
			conn = DriverManager.getConnection(getProperty(queryConstants.JDBC_URL_ICD) , getProperty(queryConstants.ICDUSERNAME), getProperty(queryConstants.ICDPASSWORD));
			stmt =  conn.createStatement();

			ICDDBStatus = true;

		} catch (ClassNotFoundException e) {
			// Log the Exception
			logger.error(LoggerUtility.MapICDException, LoggerUtility.createErrorMessage(e));
			ICDDBStatus = false;
		} catch (Exception e) {
			// Log the Exception
			logger.error(LoggerUtility.MapICDException, LoggerUtility.createErrorMessage(e));
			ICDDBStatus = false;
		}

	}




	/**
	 * Gets status of connection to ICD-10 database.
	 * @return
	 * boolean - true/false as per ICD-10 database connection status
	 */
	public boolean getICDDBSatus(){
		return ICDDBStatus;
	}

	/**
	 * Gets ICD-10 term corresponding to the provided ICD-10 code.
	 * @param code
	 * String - ICD-10 code
	 * @return
	 * String - ICD-10 term
	 */
	public String getICDTerm(String code) {
        Logger logger = LogManager.getLogger(ICDDBManager.class);

		String query = getProperty(queryConstants.ICDQUERY);
		query = query.replaceAll("[?]", code);

		try {
			ResultSet result = stmt.executeQuery(query);

			if(null!=result){
				if(result.next()){
					return result.getString(1);
				}
			}

		} catch (Exception e) {
			logger.error(LoggerUtility.MapICDException, LoggerUtility.createErrorMessage(e));
		}
		return null;
	}

	/**
	 * Gets list of the parameters to be read from the ICD properties file
	 */
	 static class queryConstants {
		public static final String ICDUSERNAME = "icd.db.username";
		public static final String ICDPASSWORD = "icd.db.password";
		public static final String JDBC_URL_ICD = "jdbc_url_icd";

		public static final String ICDDRIVERNAME = "icd.jdbc.driver.class";
		public static final String ICDJARNAME = "icd.jar.name";
		public static final String ICDQUERY = "icd.query";
	}
}
