package com.agilex.healthcare.schedulingmanager.mdws;

import com.agilex.healthcare.mobilehealthplatform.domain.PatientIdentifier;
import com.agilex.healthcare.schedulingmanager.mdws.connection.EmrConnection;
import com.agilex.healthcare.schedulingmanager.mdws.connection.EmrConnectionManager;
import com.agilex.healthcare.schedulingmanager.mdws.connection.EmrConnectionManagerFactory;
import com.agilex.healthcare.schedulingmanager.mdws.connection.MdwsConfiguration;
import com.agilex.healthcare.schedulingmanager.mdws.connection.MdwsConfigurationHelper;
import com.agilex.healthcare.schedulingmanager.mdws.generatedwsdl.emrservice.PatientTO;

public class MdwsEmrDataLayer {

	private static final String CDW_SITECODE = "204";

	protected MdwsConfiguration mdwsConfiguration;
	
	protected MdwsEmrDataLayer(MdwsConfiguration mdwsConfiguration) {
		this.mdwsConfiguration = mdwsConfiguration;
	}

	protected EmrConnection getAuthenticatedConnection(String siteCode) {
		EmrConnectionManager connectionManager = EmrConnectionManagerFactory.getInstance();
		return connectionManager.getAuthenticatedSiteConnection(mdwsConfiguration, siteCode);
	}

	/**
	 * Calls the MDWS service SchedulingSvc.select for the given patient
	 */
	protected EmrConnection getAuthenticatedConnectionWithPatientSelect(PatientIdentifier patientIdentifier) {
		String siteCode = null;

		if ("ICN".equals(patientIdentifier.getAssigningAuthority())) {
			siteCode = CDW_SITECODE;
		} else {
			siteCode = new MdwsConfigurationHelper().extractSiteCodeFromAssigningAuthority(patientIdentifier.getAssigningAuthority());
		}

		String patientId = patientIdentifier.getUniqueId();
		EmrConnection connection = getAuthenticatedConnectionWithPatientSelect(siteCode, patientId);
		return connection;
	}

	/**
	 * Calls the MDWS service SchedulingSvc.select for the given patient
	 */
	protected EmrConnection getAuthenticatedConnectionWithPatientSelect(String siteCode, String patientId) {
        EmrConnection connection = getAuthenticatedConnection(siteCode);
        
        PatientTO result = null;
		try {
			result = connection.getPort().select(patientId);
		}
		catch (Exception e) {
			throw new MdwsResponseException(MdwsResponseFaultTOFilter.getResponseType(e.getMessage()), e.getMessage());
		}
		
        if (result.getFault() != null) {
			throw new MdwsResponseException(result.getFault());
        }
        return connection;
    }

}
