
package gov.va.med.cds.response.strategy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class SensitivePatientAccessBlobStrategy extends ReferenceMappingVistaResponseBlobStrategy {

	@Override
	public Element formatResponse(List<Map<String, Object>> resultList, String domainEntryPoint, String templateId)
			throws Exception {

		Element results = DocumentHelper.createElement("results");

		results.addElement("patientDataAccessedEvent");

		Element sensitivePatientAccess = results.element("patientDataAccessedEvent");

		Document testDocument = DocumentHelper.parseText(extractSensitivePatientAccessBlobData(resultList));

		List<Element> blobElementList = testDocument.getRootElement().elements();

		for (Element blobElement : blobElementList) {
			sensitivePatientAccess.add(blobElement.detach());
		}

		return sensitivePatientAccess;
	}

	private String extractSensitivePatientAccessBlobData(List<Map<String, Object>> resultList) throws IOException {

		
		BufferedReader reader = new BufferedReader(
				new InputStreamReader(new java.io.ByteArrayInputStream((byte[]) resultList.get(0).get("stream"))));

		String readLine = null;
		StringBuffer response = new StringBuffer();
		response.append("<patient>");
		response.append("<identifier>");
		String params = ( String )resultList.get( 0 ).get( "params" );
		String patientId = params.substring(StringUtils.ordinalIndexOf(params, ",", 1)+1,StringUtils.ordinalIndexOf(params, ",", 2));
		response.append("<identity>").append(patientId).append("</identity>");
		response.append("<assigningFacility>").append(( String )resultList.get( 0 ).get( "siteID" )).append("</assigningFacility>");
		response.append("<assigningAuthority>").append("USVHA").append("</assigningAuthority>");
		response.append("</identifier>");
		response.append("</patient>");

		do {
			readLine = reader.readLine();

			if (readLine != null) {
				response = response.append(readLine);
			}
		} while (readLine != null);

		return "<temp>" + response.toString() + "</temp>";

	}
}