/*
 * Copyright (c) eHealth
 */
package be.ehealth.businessconnector.ehbox.v3.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import be.ehealth.businessconnector.ehbox.api.domain.Addressee;
import be.ehealth.businessconnector.ehbox.api.domain.Document;
import be.ehealth.businessconnector.ehbox.api.domain.DocumentMessage;
import be.ehealth.businessconnector.ehbox.api.utils.QualityType;
import be.ehealth.businessconnector.ehbox.v3.EhboxTestDataBuilder;
import be.ehealth.businessconnector.ehbox.v3.EhboxTestUtilities;
import be.ehealth.businessconnector.ehbox.v3.builders.BuilderFactory;
import be.ehealth.businessconnector.ehbox.v3.builders.SendMessageBuilder;
import be.ehealth.technicalconnector.generic.session.GenericService;
import be.ehealth.technicalconnector.generic.session.GenericSessionServiceFactory;
import be.ehealth.technicalconnector.handler.LoggingHandler;
import be.ehealth.technicalconnector.idgenerator.IdGeneratorFactory;
import be.ehealth.technicalconnector.session.Session;
import be.ehealth.technicalconnector.utils.IdentifierType;
import be.ehealth.technicalconnector.ws.domain.GenericRequest;
import be.ehealth.technicalconnector.ws.domain.HandlerChain;
import be.ehealth.technicalconnector.ws.domain.HandlerPosition;
import be.ehealth.technicalconnector.ws.domain.TokenType;
import be.fgov.ehealth.commons.core.v1.LocalisedString;
import be.fgov.ehealth.ehbox.consultation.protocol.v3.GetFullMessageRequest;
import be.fgov.ehealth.ehbox.consultation.protocol.v3.GetFullMessageResponse;
import be.fgov.ehealth.ehbox.consultation.protocol.v3.Message;
import be.fgov.ehealth.ehbox.publication.protocol.v3.SendMessageRequest;
import be.fgov.ehealth.ehbox.publication.protocol.v3.SendMessageResponse;
import be.fgov.ehealth.technicalconnector.tests.session.SessionInitializer;
import be.fgov.ehealth.technicalconnector.tests.utils.TestPropertiesLoader;


/**
 * Test for the generic service
 * 
 * @author EHP
 * 
 */
public class GenericEhboxIntegrationTest {

    @BeforeClass
    public static void removeOutOfOffices() throws Exception {
        Properties props = TestPropertiesLoader.getProperties(FILE_AS_DOC);
        Assume.assumeTrue(EhboxTestUtilities.isDoctorTest(props));
        SessionInitializer.init(props, true);
    }


    @AfterClass
    public static void unloadSession() throws Exception {
        Session.getInstance().unloadSession();
    }

    private static final String FILE_AS_DOC = "/be.ehealth.businessconnector.ehboxv3.test.properties";

    private static final Logger LOG = LoggerFactory.getLogger(PublicationServiceIntegrationTest.class);


    /**
     * Returns the destination
     * 
     * @return
     */
    private List<Addressee> getDestination() {
        List<Addressee> addresseeList = new ArrayList<Addressee>();
        Addressee addressee = new Addressee(IdentifierType.SSIN);
        addressee.setId(EhboxTestDataBuilder.getInssUser1());
        addressee.setQuality(QualityType.DOCTOR_SSIN);
        addresseeList.add(addressee);

        return addresseeList;
    }

    /**
     * Sends an encrypted document with annex and verifies the response.
     * 
     * @throws Exception
     */
    @Test
    public void testSendEncryptedDocumentWithAnnexGeneric() throws Exception {


        /*
         * Create the parameters of the new message
         */
        SendMessageBuilder builder = BuilderFactory.getSendMessageBuilder();

        DocumentMessage<Message> documentMsg = new DocumentMessage<Message>();
        documentMsg.setDestinations(getDestination());
        documentMsg.setImportant(false);
        documentMsg.setEncrypted(true);

        documentMsg.setFreeText("Free text:" + UUID.randomUUID());
        documentMsg.setPatientInss(EhboxTestDataBuilder.getInssUser1());
        documentMsg.setId(IdGeneratorFactory.getIdGenerator().generateId());

        Document doc = new Document();
        doc.setTitle("Encrypted document " + new Date());
        doc.setContent(PublicationServiceIntegrationTest.class.getResourceAsStream(FILE_AS_DOC));
        doc.setMimeType("text/plain");
        doc.setFilename("be.ehealth.businessconnector.properties");
        documentMsg.setDocument(doc);

        Document annex = new Document();
        annex.setTitle("properties");
        annex.setContent(PublicationServiceIntegrationTest.class.getResourceAsStream(FILE_AS_DOC));
        annex.setFilename("be.ehealth.technicalconnector.properties");
        annex.setMimeType("text/plain");
        documentMsg.getAnnexList().add(annex);


        GenericRequest request = new GenericRequest();
        request.setEndpoint("https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");
        SendMessageRequest messageRequest = builder.buildMessage(documentMsg);
        request.setPayload(messageRequest);
        request.setCredentialFromSession(TokenType.SAML);

        GenericService service = GenericSessionServiceFactory.getGenericService();


        SendMessageResponse response = service.send(request).asObject(SendMessageResponse.class);


        /*
         * Verify the response
         */
        // check if there are no errors
        Assert.assertEquals("100", response.getStatus().getCode());
        // check if a messageId has been returned
        Assert.assertNotNull(response.getId());

        LOG.debug("Message Sent: " + response.getId());
        for (LocalisedString localisedString : response.getStatus().getMessages()) {
            LOG.debug("statusMessage: " + localisedString.getValue());
        }
        Assert.assertTrue(response.getStatus().getMessages().size() == 1);
        Assert.assertEquals(response.getStatus().getMessages().get(0).getValue(), "SUCCESS");


        String source = "INBOX";

        String fullMessageId = response.getId();

        GetFullMessageRequest fullRequestMsg = new GetFullMessageRequest();

        fullRequestMsg.setSource(source);
        fullRequestMsg.setMessageId(fullMessageId);


        GenericRequest fullRequest = new GenericRequest();
        fullRequest.setEndpoint("https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
        fullRequest.setPayload(fullRequestMsg);
        fullRequest.setCredentialFromSession(TokenType.SAML);

        fullRequest.setDefaultHandlerChain();
        final HandlerChain handlers = new HandlerChain();
        handlers.register(HandlerPosition.AFTER, new LoggingHandler());
        fullRequest.setHandlerChain(handlers);

        EhboxTestUtilities.waitForProcessing();
        GetFullMessageResponse fullResponse = service.send(fullRequest).asObject(GetFullMessageResponse.class);

        /*
         * Verify the response
         */

        // check if the message has been returned
        Assert.assertNotNull(fullResponse.getMessage().getPublicationId());
        be.ehealth.businessconnector.ehbox.api.domain.Message<GetFullMessageResponse> msg = BuilderFactory.getConsultationMessageBuilder().buildFullMessage(fullResponse);
        Assert.assertNotNull(msg);
        LOG.debug(msg.toString());
        DocumentMessage<?> docMsg = (DocumentMessage<?>) msg;
        LOG.debug(new String(docMsg.getDocument().getContent()));

    }
}
