/*
 * Copyright (c) eHealth
 */
package be.ehealth.businessconnector.chapterIV.integration;

import java.io.InputStream;
import java.util.List;

import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;

import be.ehealth.business.kmehrcommons.helper.ErrorTypeManagement;
import be.ehealth.businessconnector.chapterIV.builders.AdmissionBuilder;
import be.ehealth.businessconnector.chapterIV.builders.BuilderFactory;
import be.ehealth.businessconnector.chapterIV.domain.ChapterIVBuilderResponse;
import be.ehealth.businessconnector.chapterIV.domain.ChapterIVKmehrResponseWithTimeStampInfo;
import be.ehealth.businessconnector.chapterIV.domain.ChapterIVReferences;
import be.ehealth.businessconnector.chapterIV.exception.ChapterIVBusinessConnectorException;
import be.ehealth.businessconnector.chapterIV.session.ChapterIVService;
import be.ehealth.businessconnector.chapterIV.session.ChapterIVSessionServiceFactory;
import be.ehealth.businessconnector.chapterIV.testutil.TestUtils;
import be.ehealth.businessconnector.chapterIV.utils.FolderTypeUtils;
import be.ehealth.technicalconnector.exception.ConnectorException;
import be.ehealth.technicalconnector.exception.SessionManagementException;
import be.ehealth.technicalconnector.exception.SoaErrorException;
import be.ehealth.technicalconnector.exception.TechnicalConnectorException;
import be.ehealth.technicalconnector.exception.UnsealConnectorException;
import be.ehealth.technicalconnector.utils.ConnectorIOUtils;
import be.fgov.ehealth.chap4.protocol.v1.AskChap4MedicalAdvisorAgreementResponse;
import be.fgov.ehealth.medicalagreement.core.v1.Kmehrresponse;
import be.fgov.ehealth.standards.kmehr.schema.v1.ErrorType;
import be.fgov.ehealth.standards.kmehr.schema.v1.FolderType;


/**
 * Integration test for ChapterIV business connector
 * 
 * @author EHP
 * 
 */
public class ChapterIVAdmissionIntegrationTest extends AbstractChapterIVTestBase {

    @BeforeClass
    public static void assumeDoctor() throws Exception {
        Assume.assumeTrue(isDoctor());
    }


    /**
     * 
     * @throws Exception
     */
    @Test
    public void testAdmissionValidRequestOA100() throws Exception {
        performTestAdmission("/examples/sample-chapter4-admission-request-with-ssin.xml", "57110204406");
    }

    /**
     * 
     * @throws Exception
     */
    @Test
    public void testAdmissionValidRequestOA100NoAgreementStartdate() throws Exception {
        performTestAdmission("/examples/sample-chapter4-admission-request-without-agreementstartdate.xml", "57110204406");
    }

    /**
     * 
     * @throws Exception
     */
    @Test
    public void testAdmissionValidRequestOA500() throws Exception {
        performTestAdmission("/examples/sample-chapter4-admission-request-with-ssin.xml", "76011402195");
    }

    @Test
    public void testAdmissionValidRequestOA500NoAgreementStartdate() throws Exception {
        performTestAdmission("/examples/sample-chapter4-admission-request-without-agreementstartdate.xml", "76011402195");
    }


    /**
     * @param message
     * @param agreementStartDate
     * @throws TechnicalConnectorException
     * @throws ConnectorException
     * @throws SessionManagementException
     * @throws UnsealConnectorException
     */
    private void performTestAdmission(String location, String patientInss) throws TechnicalConnectorException, ConnectorException, SessionManagementException, UnsealConnectorException {

        final InputStream xmlResourceInputStream = ConnectorIOUtils.getResourceAsStream(location);
        FolderType message = parseFolderType(xmlResourceInputStream);
        message = TestUtils.updateFolderWithAuthorAndCurrentDate(message, patientInss);
        DateTime startDate = FolderTypeUtils.retrieveConsultationStartDateOrAgreementStartDate(message);
        if (startDate == null) {
            startDate = new DateTime();
        }

        ChapterIVService service = ChapterIVSessionServiceFactory.getChapterIVService();
        try {
            ChapterIVReferences references = new ChapterIVReferences(true);
            AdmissionBuilder builder = BuilderFactory.getBuilderFactoryForSession().getAdmissionBuilder();
            ChapterIVBuilderResponse builderResponse = builder.build(message, true, references, startDate);

            AskChap4MedicalAdvisorAgreementResponse response = service.askChap4MedicalAdvisorAgreementResponse(builderResponse.getAskChap4MedicalAdvisorAgreementRequest());
            final ChapterIVKmehrResponseWithTimeStampInfo retrievedKmehrResponse = getResponseBuilder().validateTimestampAndretrieveChapterIVKmehrResponseWithTimeStampInfo(response);
            Assert.assertNotNull(retrievedKmehrResponse);
            Kmehrresponse kmehrresponse = retrievedKmehrResponse.getKmehrresponse();
            Assert.assertNotNull(kmehrresponse);
            Assert.assertNotNull(kmehrresponse.getRequest());
            Assert.assertNotNull(kmehrresponse.getRequest().getKmehrmessage());
            Assert.assertNotNull(retrievedKmehrResponse.getTimeStampResponse());
            Assert.assertNotNull(retrievedKmehrResponse.getKmehrResponseBytes());
            Assert.assertNotNull(retrievedKmehrResponse.getTimeStampBytes());
            List<ErrorType> errors = kmehrresponse.getAcknowledge().getErrors();
            Assert.assertTrue(ErrorTypeManagement.printErrors(errors), errors.isEmpty());
        } catch (SoaErrorException e) {
            processError(e, "AdmissionValid");
        } catch (ChapterIVBusinessConnectorException e) {
            processChapterIvBusinessException(service, e);
        }
    }
}
