package in.cdac.medinfo.csnotk.csnolib.db;

import in.cdac.medinfo.csnotk.csnolib.agents.LuceneSearchAgent;
import in.cdac.medinfo.csnotk.csnolib.commons.Constants;
import in.cdac.medinfo.csnotk.csnolib.commons.DBSchemaMapping;
import in.cdac.medinfo.csnotk.csnolib.util.PropertyReader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.SQLException;
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;

public class RefsetDBCreator {
    private static final Logger logger = LogManager.getLogger(RefsetDBCreator.class);

	public static void main(String[] args) {

		Connection conn;
		Statement stm;
		String refsetFile=null;
		String refsetId = null;

		LuceneSearchAgent searchAgent = new LuceneSearchAgent();

		PropertyReader.loadSystemProperties();
		File refsetDir = new File(PropertyReader.getProperty(Constants.REFSET_DIR));
		if(!refsetDir.exists())
		{
			logger.error(LoggerUtility.ConsoleWithException, "Wrong directory provided for SNOMED CT release files");
			System.exit(0);
		}

		File[] files_refset = new File(PropertyReader.getProperty(Constants.REFSET_DIR)+File.separator+"Refset"+File.separator+"Content").listFiles();
		for (File file : files_refset) {
			if(file.getName().matches("der2_Refset(.*)"))
				refsetFile=file.getAbsolutePath();
		}

		if(refsetFile==null){

			logger.error(LoggerUtility.ConsoleWithException, "Wrong directory provided for SNOMED CT release files");
			System.exit(0);
		}

		try {
			BufferedReader in = new BufferedReader(new FileReader(refsetFile));
			in.readLine();
			String[] tokens = in.readLine().split("\t");
			refsetId=tokens[4];
			in.close();
		} catch (Exception e) {
			//Log the Exception
			logger.error(LoggerUtility.Exception, LoggerUtility.createErrorMessage(e));
		}

		logger.info(LoggerUtility.ConsoleWithLog, "Please wait for refset db creation.");
		try {
			conn=ConnectionManager.getConnection();
			stm=conn.createStatement();
			stm.execute("Delete from "+DBSchemaMapping.REFSET+" where "+DBSchemaMapping.REFSET_REFSET_ID+" = "+refsetId);
			stm.execute("insert into "+DBSchemaMapping.REFSET+" SELECT * FROM CSVREAD('"+refsetFile+"',null,'charset=UTF-8 fieldDelimiter= fieldSeparator='||chr(9));");
			logger.info(LoggerUtility.ConsoleWithLog, "Refset database created successfully.");
		} catch (SQLException e) {
			//Log the Exception
			logger.error(LoggerUtility.Exception, LoggerUtility.createErrorMessage(e));
		}

		searchAgent.deleteIndex(refsetId);
		searchAgent.createIndex(refsetId,null,false,false);
	}

}
