/*
 * Copyright (c) eHealth
 */
using System;
using be.ehealth.technicalconnector.session;
using be.ehealth.technicalconnector.utils;
using ikvm.extensions;
using NUnit.Framework;
using be.ehealth.business.common.domain;
using be.ehealth.businessconnector.dmg.builders;
using be.ehealth.businessconnector.dmg.session;
using be.ehealth.businessconnector.dmg.domain;
using be.fgov.ehealth.globalmedicalfile.protocol.v1;
using be.fgov.ehealth.messageservices.core.v1;
using be.fgov.ehealth.standards.kmehr.id.v1;
using be.fgov.ehealth.standards.kmehr.schema.v1;
using be.fgov.ehealth.standards.kmehr.cd.v1;
using be.fgov.ehealth.technicalconnector.tests.utils;
using be.fgov.ehealth.technicalconnector.tests.session;

namespace be.ehealth.businessconnector.dmg.integration
{
	/**
	 * Consult Integration Test
	 * 
	 * @author EHP
	 * 
	 */
	[TestFixture]
	public class DmgConsultationIntegrationTest
	{
		[SetUp]
		public static void init() {
			SessionInitializer.init(".\\be.ehealth.businessconnector.dmg.test.properties", SupportedLanguages.NET.getAbbreviation());
			
		}
		
		[TearDown]
		public static void tearDown() {
			Session.getInstance().unloadSession();
		}
		
		[Test]
		public void testOA300() {
			baseConsultationTest("Madeleine", "De Maret", "300", null, "59120346292", new org.joda.time.DateTime());
		}
		
		[Test]
		public void testOA600() {
			baseConsultationTest("Ajse", "Osmani", "600", null, "05041001640", new org.joda.time.DateTime());
		}
		
		public void baseConsultationTest(String firstname, String lastName, String mutuality, String regNrWithMut, String inss, org.joda.time.DateTime dmgStartDate) {
			bool istest = true;
			
			DMGReferences reference = new DMGReferences(true);
			
			Patient pI = new Patient();
			pI.setFirstName(firstname);
			pI.setLastName(lastName);
			pI.setMutuality(mutuality);
			pI.setRegNrWithMut(regNrWithMut);
			pI.setInss(inss);
			
			org.joda.time.DateTime dateReference = new org.joda.time.DateTime();
			byte[] expected = ConnectorIOUtils.getBytes(ConnectorIOUtils.getResourceAsStream(".\\templates\\RetrieveTransactionRequest.select.xml"));
			
			MarshallerHelper kmehrRequestMarshaller = new MarshallerHelper(typeof(SelectRetrieveTransaction), typeof(SelectRetrieveTransaction));
			SelectRetrieveTransaction request = (SelectRetrieveTransaction)kmehrRequestMarshaller.toObject(expected);
			
			
			PatientType patient = new PatientType();
			IDPATIENT idpatient = new IDPATIENT();
			
			if (inss != null && !inss.isEmpty()) {
				idpatient.setSV("1.0");
				idpatient.setValue(pI.getInss());
				idpatient.setS(IDPATIENTschemes.ID_PATIENT);
				patient.getIds().add(idpatient);
			}
			
			MemberinsuranceType member = new MemberinsuranceType();
			
			if (pI.getRegNrWithMut() != null) {
				member.setMembership(pI.getRegNrWithMut());
				if (pI.getMutuality() != null) {
					IDINSURANCE id = new IDINSURANCE();
					id.setSV("1.0");
					id.setValue(pI.getMutuality());
					member.setId(id);
				}
			}
			if (member.getId() != null || member.getMembership() != null) {
				patient.setInsurancymembership(member);
			}
			// patient.setFamilyname(pI.getLastName());
			// patient.getFirstnames().add(pI.getFirstName());
			
			
			request.setPatient(patient);
			request.getTransaction().setBegindate(dmgStartDate);
			
			
			RequestObjectBuilder builder = RequestObjectBuilderFactory.getRequestObjectBuilder();
			ConsultGlobalMedicalFileRequest result = builder.buildSendConsultRequest(istest, reference, pI, dateReference, request);

			
			ConnectorXmlUtils.logXmlObject(result);
			
			DmgService service = DmgSessionServiceFactory.getDmgService();
			SendResponseType resp = service.consultGlobalMedicalFile(result);
			
			
			ResponseObjectBuilder respBuilder = ResponseObjectBuilderFactory.getResponseObjectBuilder();
			DmgBuilderResponse response = respBuilder.handleSendResponseType(resp);
			
			Assert.AreEqual("200", response.getEhealthStatus(), "Status code not 200");
			
			RetrieveTransactionResponse retrieveTransactionResponse = response.getRetrieveTransactionResponse();
			Assert.IsNotNull(retrieveTransactionResponse);
			AcknowledgeType acknowledge = retrieveTransactionResponse.getAcknowledge();
			Assert.IsNotNull(acknowledge);
			java.util.List errors = acknowledge.getErrors();
			String errorCodes = "";
			if (errors != null && !errors.isEmpty()) {
				for (int i = 0; i < errors.size(); i++) {
					ErrorMyCarenetType errorType = (ErrorMyCarenetType)errors.get(i);
					java.lang.StringBuilder sb = new java.lang.StringBuilder();
					sb.append("errorCds : [");
					for (int j = 0; j< errorType.getCds().size(); j++) {
						CDERRORMYCARENET errorCd = (CDERRORMYCARENET)errorType.getCds().get(j);
						sb.append(" [" + errorCd.getValue()).append("] ");
					}
					errorCodes = sb.toString() + "]";
					sb.append("], url:[").append(errorType.getUrl());
					sb.append("] , description:[" + errorType.getDescription() != null ? errorType.getDescription().getValue() : "empty description" + "]");
					
				}
			}
			Assert.IsNotNull(retrieveTransactionResponse.getKmehrmessage(), errorCodes);
			
			java.util.Map resultMap = response.getResult();
			Assert.IsNotNull(resultMap.get(DmgBuilderResponse.RESULT_AS_BYTE));
			Assert.IsNotNull(resultMap.get(DmgBuilderResponse.RESULT_EHEALTH_STATUS));
			Assert.IsNotNull(resultMap.get(DmgBuilderResponse.RESULT_HAS_SIGNATURE));
			Assert.IsNotNull(resultMap.get(DmgBuilderResponse.RESULT_ORGINAL));
			Assert.IsNull(resultMap.get(DmgBuilderResponse.RESULT_SIGINATURE_VERIFICATION));
			Assert.AreEqual("200", resultMap.get(DmgBuilderResponse.RESULT_EHEALTH_STATUS));
			Assert.AreEqual(java.lang.Boolean.FALSE, resultMap.get(DmgBuilderResponse.RESULT_HAS_SIGNATURE));

		}
	}
}
