package gov.va.med.cds.hapi;

import java.util.Date;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcOperations;

import gov.va.med.cds.checksum.util.IcnChecksum;
import gov.va.med.cds.util.DateTimeUtil;

public class HL7Utility {
	public static JdbcOperations jdbcTemplateForMessageControlId = null;

	private Map<String, String> facilityIdMap = null;
	private Map<String, String> sendingApplicaionDestinationMap = null;

	// SQL statements used in the application
	private static final String SQL_SELECTUNIQUEMESSAGECONTROLID = "SELECT MESSAGE_CTRL_ID_SEQ_ID.NEXTVAL FROM DUAL";

	public static String createMessageDateTime() {
		return DateTimeUtil.getISOTime(new Date().getTime(), null);
	}

	/***
	 * Message Control Id generation is done by a Oracle Sequence of maximum
	 * length 20
	 * 
	 * @return a unique Message Control Id of length 20
	 */
	public static String createMessageControlId()throws DataAccessException {
		/*return String.format("%020d", jdbcTemplateForMessageControlId
				.queryForLong(SQL_SELECTUNIQUEMESSAGECONTROLID));*/
		
		return String.format("%020d", jdbcTemplateForMessageControlId
				.queryForObject(SQL_SELECTUNIQUEMESSAGECONTROLID, Long.class));
	}

	public String getSendingFacility(String assigningFacility) {
		return facilityIdMap.get(assigningFacility);
	}
		
	public void setFacilityIdMap( Map<String, String> facilityIdMap )
    {
        this.facilityIdMap = facilityIdMap;
    }
	
	public void setSendingApplicaionDestinationMap( Map<String, String> senndingAppdMap )
    {
        this.sendingApplicaionDestinationMap = senndingAppdMap;
    }
	
	public String getSendingApplicaionDestination(String sendingApplicationKey) {
		return sendingApplicaionDestinationMap.get(sendingApplicationKey);
	}

    public static String addChecksumToIcn(String icn) {
		return IcnChecksum.addChecksumToIcn(icn);
	}

	public void setJdbcTemplateForMessageControlId(
			JdbcOperations jdbcTemplateForMessageControlId) {
		HL7Utility.jdbcTemplateForMessageControlId = jdbcTemplateForMessageControlId;
	}
}
