/*
 * Copyright (c) eHealth
 */
using System;
using NUnit.Framework;
using java.util;

using org.joda.time;

using be.ehealth.business.common.domain;
using be.ehealth.businessconnector.therlink.builders;
using be.ehealth.businessconnector.therlink.domain;
using be.ehealth.businessconnector.therlink.domain.requests;
using be.ehealth.businessconnector.therlink.domain.responses;
using be.ehealth.businessconnector.therlink.exception;
using be.ehealth.businessconnector.therlink.mappers;
using be.ehealth.businessconnector.therlink.service;
using be.ehealth.businessconnector.therlink.util;
using be.ehealth.technicalconnector.config;
using be.ehealth.technicalconnector.exception;
using be.ehealth.technicalconnector.service.sts.security;
using be.ehealth.technicalconnector.session;
using be.ehealth.technicalconnector.session.impl;

namespace be.ehealth.businessconnector.therlink.service.impl
{
    /**
     * Unit test for {@link TherLinkService}
     * 
     * @author EHP
     * 
     */
    [TestFixture]
    public class TherlinkServiceBasicUserIntegrationTest : AbstractTherlinkIsolationIntegrationTest
    {
        private static String MAIN_KMEHR_QUALITY = "main.kmehr.quality";

        private static string linkType;
        
        private static HcParty concernedHealthCareProfessional;
        
        [SetUp]
        public static void init() {
            ConfigValidator configValidator = ConfigFactory.getConfigValidator();
            linkType = TherapeuticLinkTypeValues.valueOf(configValidator.getProperty(MAIN_KMEHR_QUALITY).ToUpper()).getTherlinkType();
            concernedHealthCareProfessional = ConfigReader.getCareProvider();
        }
        
        
        public void removeExistingLinks() {
            TherlinkTestUtils.revokeNonReferrals(TherlinkTestUtils.getOfflinePatient());
        }
        
        [Test]
        public void putTherapeuticLink() {
            removeExistingLinks();
            TherLinkService therLinkService = ServiceFactory.getTherLinkService();
            SAMLToken samlToken = Session.getInstance().getSession().getSAMLToken();
            
            Proof proof = RequestObjectBuilderFactory.getProofBuilder().createProofForEidReading();
            be.ehealth.business.common.domain.Patient patient = TherlinkTestUtils.fillTherlinkPatientWithOfflinePatientDataForProof(proof);
            
            PutTherapeuticLinkRequest request = RequestObjectBuilderFactory.getRequestObjectBuilder().createPutTherapeuticLinkRequest(null, patient, concernedHealthCareProfessional, linkType, null, proof);
            
            be.fgov.ehealth.hubservices.core.v2.PutTherapeuticLinkRequest mapPutTherapeuticLinkRequest = MapperFactory.getRequestObjectMapper().mapPutTherapeuticLinkRequest(request);
            
            be.fgov.ehealth.hubservices.core.v2.PutTherapeuticLinkResponse putTherapeuticLink = therLinkService.putTherapeuticLink(samlToken, mapPutTherapeuticLinkRequest);
            PutTherapeuticLinkResponse response = MapperFactory.getResponseObjectMapper().mapJaxbToPutTherapeuticLinkResponse(putTherapeuticLink);
            
            Console.WriteLine(response.toString());
            logResponseAndCheckIfNoErrors(response);
        }
        
        [Test]
        public void putTherapeuticLinkWithIsi() {
            removeExistingLinks();
            be.ehealth.business.common.domain.Patient patient = new be.ehealth.business.common.domain.Patient.Builder().withInss("08013126873").withFirstName("dummyname").withLastName("dummyName").withIsiPlus("9950014769").build();
            Proof isiProof = proofBuilder.createProofForIsiReading();
            TherlinkTestUtils.revokeNonReferrals(patient, isiProof);
            TherLinkService therLinkService = ServiceFactory.getTherLinkService();
            SAMLToken samlToken = Session.getInstance().getSession().getSAMLToken();
            
            PutTherapeuticLinkRequest request = requestObjectBuilder.createPutTherapeuticLinkRequest(null, patient, concernedHealthCareProfessional, linkType, null, isiProof);
            
            be.fgov.ehealth.hubservices.core.v2.PutTherapeuticLinkRequest mapPutTherapeuticLinkRequest = requestObjectMapper.mapPutTherapeuticLinkRequest(request);
            
            be.fgov.ehealth.hubservices.core.v2.PutTherapeuticLinkResponse putTherapeuticLink = therLinkService.putTherapeuticLink(samlToken, mapPutTherapeuticLinkRequest);
            PutTherapeuticLinkResponse response = responseObjectMapper.mapJaxbToPutTherapeuticLinkResponse(putTherapeuticLink);
            
            Console.WriteLine(response.toString());
            logResponseAndCheckIfNoErrors(response);
        }
        
        /**
         * @param response
         */
        private void logResponseAndCheckIfNoErrors(PutTherapeuticLinkResponse response) {
            Console.WriteLine(response.toString());
            Assert.IsNotNull(response);
            Assert.IsNotNull(response.getAcknowledge());
            Assert.IsNotNull(response.getAcknowledge().getListOfErrors());
            checkErrors(response);
        }

        /**
         * @param response
         */
        private void checkErrors(GeneralResponse response) {
            if (response.getAcknowledge().getListOfErrors().size() > 0) {
                java.lang.StringBuilder sb = new java.lang.StringBuilder();
                for (int i = 0 ; i<response.getAcknowledge().getListOfErrors().size(); i++) {
                    TherapeuticLinkResponseError error = (TherapeuticLinkResponseError)response.getAcknowledge().getListOfErrors().get(i);
                    String errorDescription = error.getErrorDescription();
                    String errorCode = error.getErrorCode();
                    sb.append(errorCode).append(" : ").append(errorDescription).append(" ");
                }
                Assert.Fail(sb.toString());
            }
        }
        
        [Test]
        public void getTherapeuticLink()  {
            removeExistingLinks();
            // create builders
            CommonObjectBuilder commonBuilder = RequestObjectBuilderFactory.getCommonBuilder();
            RequestObjectBuilder requestObjectBuilder = RequestObjectBuilderFactory.getRequestObjectBuilder();
            ProofBuilder proofBuilder = RequestObjectBuilderFactory.getProofBuilder();
            RequestObjectMapper requestObjectMapper = MapperFactory.getRequestObjectMapper();
            SAMLToken samlToken = Session.getInstance().getSession().getSAMLToken();
            ResponseObjectMapper responseObjectMapper = MapperFactory.getResponseObjectMapper();
            TherLinkService service = ServiceFactory.getTherLinkService();
            
            // retrieve all info to create therapeutic link
            String kmehrId = commonBuilder.createKmehrID();
            Date currentDate = new Date();
            Author author = commonBuilder.createAuthor(requestObjectBuilder.getAuthorHcParties());
            
            Proof proof = proofBuilder.createProofForEidReading();
            be.ehealth.business.common.domain.Patient patientInfo = TherlinkTestUtils.fillTherlinkPatientWithOfflinePatientDataForProof(proof);
            HcParty careProviderHcParty = ConfigReader.getCareProvider();
            java.util.Date endDate = new org.joda.time.DateTime().plusMonths(6).toDate();
            String careProviderHcpType = requestObjectBuilder.getEnduserHcpType();
            TherapeuticLink therapeuticLink = commonBuilder.createTherapeuticLink(patientInfo, careProviderHcpType, null, currentDate, endDate, null, careProviderHcParty);

            int maxRows = requestObjectBuilder.getMaxRows();
            
            GetTherapeuticLinkRequest request = new GetTherapeuticLinkRequest(kmehrId, currentDate, author, therapeuticLink, maxRows, proof);
            
            be.fgov.ehealth.hubservices.core.v2.GetTherapeuticLinkRequest mappedRequest = requestObjectMapper.mapGetTherapeuticLinkRequest(request);
            
            be.fgov.ehealth.hubservices.core.v2.GetTherapeuticLinkResponse getTherapeuticLinkResponse = service.getTherapeuticLink(samlToken, mappedRequest);
            GetTherapeuticLinkResponse response = responseObjectMapper.mapJaxbToGetTherapeuticLinkResponse(getTherapeuticLinkResponse);
            
            Console.WriteLine(response.toString());
            Assert.IsNotNull(response);
            Assert.IsNotNull(response.getAcknowledge());
            Assert.IsNotNull(response.getAcknowledge().getListOfErrors());
            checkErrors(response);
        }
        
        
        [Test]
        public void revokeTherapeuticLink()  {
            removeExistingLinks();
            Proof proof = proofBuilder.createProofForEidReading();
            be.ehealth.business.common.domain.Patient patient = TherlinkTestUtils.fillTherlinkPatientWithOfflinePatientDataForProof(proof);
            HcParty concernedHealthCareProfessionel = ConfigReader.getCareProvider();
            RequestObjectBuilder requestObjectBuilder = RequestObjectBuilderFactory.getRequestObjectBuilder();
            ResponseObjectMapper responseObjectMapper = MapperFactory.getResponseObjectMapper();
            RequestObjectMapper requestObjectMapper = MapperFactory.getRequestObjectMapper();

            TherLinkService service = ServiceFactory.getTherLinkService();
            PutTherapeuticLinkRequest putRequest = requestObjectBuilder.createPutTherapeuticLinkRequest(patient, concernedHealthCareProfessionel, linkType, proof);
            TherapeuticLink therlink = putRequest.getLink();
            service.putTherapeuticLink(SessionManagerImpl.getInstance().getSession().getSAMLToken(), MapperFactory.getRequestObjectMapper().mapPutTherapeuticLinkRequest(putRequest));

            RevokeTherapeuticLinkRequest request = requestObjectBuilder.createRevokeTherapeuticLinkRequest(patient, concernedHealthCareProfessionel, new Date(), null, linkType, null, proofBuilder.createProofForEidReading());
            
            SAMLToken samlToken = Session.getInstance().getSession().getSAMLToken();
            be.fgov.ehealth.hubservices.core.v2.RevokeTherapeuticLinkRequest mapRevokeTherapeuticLinkRequest = requestObjectMapper.mapRevokeTherapeuticLinkRequest(request);
            be.fgov.ehealth.hubservices.core.v2.RevokeTherapeuticLinkResponse revokeTherapeuticLink = service.revokeTherapeuticLink(samlToken, mapRevokeTherapeuticLinkRequest);
            RevokeTherapeuticLinkResponse response = responseObjectMapper.mapJaxbToRevokeTherapeuticLinkResponse(revokeTherapeuticLink);

            
            Console.WriteLine(response.toString());
            Assert.IsNotNull(response);
            Assert.IsNotNull(response.getAcknowledge());
            Assert.IsNotNull(response.getAcknowledge().getListOfErrors());
            checkErrors(response);
        }
    }
}
