using be.ehealth.business.mycarenetdomaincommons.domain;
using be.ehealth.businessconnector.genericasync.domain;
using be.ehealth.businessconnector.mycarenet.memberdataasync.session;
using be.ehealth.technicalconnector.exception;
using be.ehealth.technicalconnector.utils;
using be.fgov.ehealth.technicalconnector.tests.utils;
using be.fgov.ehealth.technicalconnector.tests.session;
using org.apache.commons.io;
using javax.xml.ws.soap;
using java.io;
using java.util.concurrent;

using NUnit.Framework;
using System;

namespace be.ehealth.businessconnector.memberdataasync.session.regional
{
	
	public abstract class AbstractAsyncIntegrationTest {
	
	    private static string REQUEST_FOLDER = ".\\examples\\memberdata\\async\\request\\regional\\";

	    private static string VALID_REQUEST = "anh-request-detail.xml";

	    private static int SLEEP_TIME = 70;
	
	    private MemberDataService memberDataService;

	
	    public AbstractAsyncIntegrationTest(MemberDataService memberDataService) {
	        this.memberDataService = memberDataService;
	    }

	    [Test]
	    public void postMDAEncrypted() {
	        testValidPost(true);
	    }
	
	    [Test]
	    public void postMDA() {
	        testValidPost(false);
	    }
	
	    private void testValidPost(bool isEncrypted) {
	    	confirmAllMessages(getResponse());
	        postRequest("AAA1130000", VALID_REQUEST, isEncrypted);
	        ProcessedGetResponse response = getResponse();
	        confirmAllMessages(response);
	        verifyResponse(response);
	    }
	
	    private void verifyResponse(ProcessedGetResponse response) {
	        Assert.IsFalse(response.getMsgResponses().isEmpty());
	    }
	
	    private void postRequest(string id, string requestXml, bool isEncrypted) {
	        byte[] bytes = ConnectorIOUtils.getResourceAsByteArray(REQUEST_FOLDER + requestXml);
	        InputReference inputReference = new InputReference(id);
	        if (isEncrypted) {
	            memberDataService.postEncryptedMDAXml(bytes, inputReference);
	        } else {
	            memberDataService.postMDAXml(bytes, inputReference);
	        }
	        waitSomeTimeBeforeProceeding();
	    }
	
	    private ProcessedGetResponse getResponse() {
	        ProcessedGetResponse response = memberDataService.getMDAXml(GetRequest.newBuilder().withDefaults().build());
	        return response;
	    }
	
	    private void confirmAllMessages(ProcessedGetResponse response) {
	    	java.util.List msgResponses = response.getMsgResponses();
	    	for (int i=0; i<msgResponses.size(); ++i) {
	    		ProcessedMsgResponse msgResponse = (ProcessedMsgResponse) msgResponses.get(i);
	    		memberDataService.confirmMessage(msgResponse);
	    	}
	    }
	
	    private void waitSomeTimeBeforeProceeding() {
	        TimeUnit.SECONDS.sleep(SLEEP_TIME);
	    }
	
	}

}
