/*******************************************************************************
 * 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.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import in.cdac.medinfo.csnotk.csnolib.agents.SNOMEDAgent;
import in.cdac.medinfo.csnotk.csnolib.icdmap.ICDMapAgent;
import in.cdac.medinfo.csnotk.csnolib.icdmap.MapAdvice;
import in.cdac.medinfo.csnotk.csnolib.icdmap.MapGroup;
import in.cdac.medinfo.csnotk.csnolib.icdmap.MapResult;
import in.cdac.medinfo.csnotk.csnolib.icdmap.Record;
//Logs
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import in.cdac.medinfo.csnotk.csnolib.util.LoggerUtility;

/**
 * ICDMapAgentMapAPI class contains the sample code for implementing the SNOMED CT to ICD-10 map API.
 *
 */
public class ICDMapAgentMapAPI {

	/**
	 * main method
	 * @param args
	 */
	public static void main(String[] args) {

		Logger logger;
		Record record = new Record();
		SNOMEDAgent agent = new SNOMEDAgent();
		ICDMapAgent mapAgent = new ICDMapAgent();

		try {
			agent.init();
            logger = LogManager.getLogger(ICDMapAgentMapAPI.class);
            logger.info(LoggerUtility.CONSOLE, "Sample for Map API");
			logger.info(LoggerUtility.CONSOLE, "Do you want to create SNOMED CT to ICD map database (y/n)");
			BufferedReader serviceInput = new BufferedReader(new InputStreamReader(System.in));

				String dbOverride = serviceInput.readLine();
				if(dbOverride.equalsIgnoreCase("y"))
				{
					logger.info(LoggerUtility.CONSOLE, "Please Enter SNOMED CT Release file path till Snapshot");
					String snomedDirPath=serviceInput.readLine();
					mapAgent.createICDMapdb(snomedDirPath, true);
				}

			logger.info(LoggerUtility.CONSOLE, "Please enter details for mapping SNOMED CT to ICD-10 code:");

			/**
			 * referenceComponentInput takes SNOMED concept id  as input from the user.
			 * The input is to be converted from SNOMED CT to ICD-10 code.
			 */
			logger.info(LoggerUtility.CONSOLE, "Enter primary cptid :");
			BufferedReader referenceComponentInput = new BufferedReader(
					new InputStreamReader(System.in));
			// converts the user input to long value
			Long referenceComponent = Long.parseLong(referenceComponentInput.readLine());
			record.setPrimarySCTID(referenceComponent);

			//inputs the secondary diagnosis -  SNOMED Concept id
			logger.info(LoggerUtility.CONSOLE, "Enter secondary cptid :");
			BufferedReader secondaryInput = new BufferedReader(
					new InputStreamReader(System.in));
			//converts the user input to string value
			String secondary = secondaryInput.readLine();
			record.setSecondarySCTID(secondary);

			//inputs the gender of the patient (male, female, blank)
			logger.info(LoggerUtility.CONSOLE, "Enter gender :");
			BufferedReader genderInput = new BufferedReader(
					new InputStreamReader(System.in));
			//converts the user input to string value
			String gender = genderInput.readLine();
			record.setGender(gender);

			//inputs the birth date of the patient in MM-DD-YYYY format
			logger.info(LoggerUtility.CONSOLE, "Enter birthdate (MM-DD-YYYY) :");
			BufferedReader birthdateInput = new BufferedReader(
					new InputStreamReader(System.in));
			//converts the user input to date value
			String birthdate = birthdateInput.readLine();
			if(birthdate!=null && !birthdate.equalsIgnoreCase("")){
				DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
				Date birthDate = df.parse(birthdate);
				record.setBirthDate(birthDate);
			}


			//inputs the diagnosis date on which patient was diagnosed (else assumed current date) in MM-DD-YYYY format
			logger.info(LoggerUtility.CONSOLE, "Enter diagnosisdate (MM-DD-YYYY) :");
			BufferedReader diagnosisdateInput = new BufferedReader(
					new InputStreamReader(System.in));
			//converts the user input to date value
			String diagnosisdate = diagnosisdateInput.readLine();
			if(diagnosisdate!=null && !diagnosisdate.equalsIgnoreCase("")){
				DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
				Date diagnosisDate = df.parse(diagnosisdate);
				record.setBirthDate(diagnosisDate);
			}


		}
		catch (Exception e)
		{
			// Log the Exception
			logger = LogManager.getLogger(ICDMapAgentMapAPI.class);
            logger.error(LoggerUtility.MapICDException, LoggerUtility.createErrorMessage(e));
		}

		MapResult mapResult = mapAgent.map(record);
		/**
		 * displays the output with mapping status
		 * NO_MAP_FOUND  - no map found or not successfully mapped to ICD-10 code
		 * MAP_FOUND - map found or successfully to ICD-10 code
		 * INDETERMINATE_MAP - could not determine successful ICD-10 map code
		 */
		//If logger is not initialized earlier
		logger = LogManager.getLogger(ICDMapAgentMapAPI.class);
		logger.info(LoggerUtility.CONSOLE, "Result ----");
		logger.info(LoggerUtility.CONSOLE, "Mapping status : {}" , mapResult.getMapStatus());

		List<MapGroup> mapGroup = mapResult.getMapGroup();
		//each mapGroup is traversed
		for(MapGroup mGroup : mapGroup){
			if(mGroup != null){
				logger.info(LoggerUtility.CONSOLE, "Group -");
				logger.info(LoggerUtility.CONSOLE, "Mapped ICD Code: {}" , mGroup.getMappedICDCode());
				List<MapAdvice> mapAdvices = mGroup.getMapAdvices();
				//advice and corresponding ICD-10 code within the group are displayed
				for (MapAdvice mapAdvice : mapAdvices) {
				    logger.info(LoggerUtility.CONSOLE, "Advice = {}, TargetCode = {}, ICD-10 Term = {}" , mapAdvice.getAdvice() , mapAdvice.getTarget() , mapAdvice.getTerm());
				}
			}

		}

	}
}
