/*
 * Copyright (c) eHealth
 */
using System;
using be.fgov.ehealth.technicalconnector.tests.session;
using java.lang;
using java.util;
using be.ehealth.technicalconnector.idgenerator;
using be.ehealth.technicalconnector.utils;
using be.fgov.ehealth.hubservices.core.v3;
using NUnit.Framework;
using org.joda.time;
using be.ehealth.businessconnector.hubv3.builders;
using be.ehealth.businessconnector.hubv3.service;
using be.ehealth.businessconnector.hubv3.session;
using be.ehealth.businessconnector.hubv3.helpers;
using be.ehealth.technicalconnector.exception;
using be.fgov.ehealth.standards.kmehr.cd.v1;
using be.fgov.ehealth.standards.kmehr.id.v1;
using be.fgov.ehealth.standards.kmehr.schema.v1;
using be.ehealth.technicalconnector.config;
using be.ehealth.technicalconnector.config.impl;
using be.ehealth.technicalconnector.session;
using be.fgov.ehealth.technicalconnector.tests.utils;
using be.ehealth.business.intrahubcommons.exception;
using be.ehealth.business.kmehrcommons.helper;
using be.ehealth.businessconnector.testcommons;
using org.apache.commons.lang;
using be.ehealth.business.common.domain;

namespace be.ehealth.businessconnector.hubv3.session
{
	/**
	 * Integration test for {@link HubServiceComplete}
	 * 
	 * @author EHP
	 * 
	 */
	[TestFixture]
	public class WalkThroughVitalinkIntegrationTest
	{
	    
	    private static string URI_TRANSACTION = "vitalinkuri";

	    private static HubService hubService;

	    private static Configuration technicalConfig;

	    private static Properties props;

	    private static string transactionId;
        
        private static int latestMedicationSchemeVersion;
        
        private static HubTestHelper helper;


	    [SetUp]
	    public static void initHubServiceCompleteIntegrationTest() {
		    SessionInitializer.init(".\\be.ehealth.businessconnector.intrahubv3.test.properties", SupportedLanguages.NET.getAbbreviation());
	        technicalConfig = ConfigFactory.getConfigValidator().getConfig();
	        props = TestPropertiesLoader.getProperties(".\\be.ehealth.businessconnector.intrahubv3.test.properties");
	        new ConfigurationModuleProxy().init(technicalConfig);
	        HubConfigVitalink.initConfig();
		    hubService = HubSessionServiceFactory.getHubService();
		    helper = new HubTestHelper("vitalink", new Patient.Builder().withFirstName(HubConfigVitalink.PATIENT_FIRSTNAME).withFamilyName(HubConfigVitalink.PATIENT_LASTNAME).withInss(HubConfigVitalink.PATIENT_NISS).build());
	    }


        [TearDown]
        public void tearDownIntrahubSession() {
            Session.getInstance().unloadSession();
        }


        [Test]
        public void _010_putHcPartyConsent() {
            ConsentHCPartyType consent = new ConsentHCPartyType();
            consent.setAuthor(helper.createAuthor());
            consent.setHcparty(helper.createHcPartyIdProfessional());
            consent.setRevokedate(new org.joda.time.DateTime());
            consent.setSigndate(new org.joda.time.DateTime());
            
            try {
                hubService.putHCPartyConsent(consent);
                Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
                Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }

        [Test]
        public void _020_putPatient() {
            PersonType person = helper.createPatient();
            
            try {
                hubService.putPatient(person);
                Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
                Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }

        [Test]
        public void _030_getPatient() {        
           try {
               hubService.getPatient(helper.createPatientIdType());
           } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
           }
        }

        [Test]
        public void _040_putPatientConsent() {
           ConsentType consent = helper.createConsentType();

           try {
               hubService.putPatientConsent(consent);
               Assert.Fail("Should throw unsupported error");
           } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
           }
        }

        [Test]
        public void _050_putTherapeuticLink() {
           TherapeuticLinkType therapeuticLink = helper.createTherapeuticLinkType();

           try {
               hubService.putTherapeuticLink(therapeuticLink);
               Assert.Fail("Should throw unsupported error");
           } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
           }
        }

        [Test]
        public void _060_putTransaction() {
            Kmehrmessage kmehrmessage = helper.createPutTransactionMessage();
            
            PutTransactionResponse putTransaction = hubService.putTransaction(kmehrmessage);
            transactionId = ((IDKMEHR) putTransaction.getTransaction().getIds().get(0)).getValue();

            XmlAsserter.assertSimilar(helper.expectedResponse("PutTransaction"), ConnectorXmlUtils.toString(putTransaction));
        }

        [Test]
        public void _070_getPatientConsent() {
           try {
               hubService.getPatientConsent(helper.createSelectGetPatientConsentType());
               Assert.Fail("Should throw unsupported error");
           } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
           }
        }

        [Test]
        public void _080_getTherapeuticLink() {
           try {
               hubService.getTherapeuticLink(helper.createSelectGetHCPartyPatientConsentType());
               Assert.Fail("Should throw unsupported error");
           } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
           }
        }

        [Test]
        public void _090_getTransactionList() {
            PatientIdType patientId = helper.createPatientIdType();
            GetTransactionListResponse transactionListResponse = hubService.getTransactionList(patientId, LocalSearchType.LOCAL, helper.createTransactionWithPeriodType());

            Assert.IsTrue(transactionListResponse.getKmehrheader().getFolder().getTransactions().size() > 0, "Transaction list should not be empty");
        }

        [Test]
        public void _100_getTransaction() {
            PatientIdType patientId = helper.createPatientIdType();
            GetTransactionResponse transactionResponse = hubService.getTransaction(patientId, helper.createTransactionBaseType(URI_TRANSACTION, transactionId));

            XmlAsserter.assertSimilar(helper.expectedResponse("GetTransaction"), ConnectorXmlUtils.toString(transactionResponse));
        }

        [Test]
        public void _110_revokeTransaction() {
            RevokeTransactionResponse revokeTransaction = hubService.revokeTransaction(helper.createPatientIdType(), helper.createTransactionBaseType(URI_TRANSACTION, transactionId));

            XmlAsserter.assertSimilar(helper.expectedResponse("RevokeTransaction"), ConnectorXmlUtils.toString(revokeTransaction));
        }
        
        [Test]
        public void _120_getLastestUpdate() {
            GetLatestUpdateResponse latestUpdateResponse = hubService.getLatestUpdate(helper.createSelectGetLatestUpdateType());
            latestMedicationSchemeVersion = helper.getLatestMedicationSchemeVersion(latestUpdateResponse).intValue();
           
            XmlAsserter.assertSimilar(helper.expectedResponse("GetLatestUpdate"), ConnectorXmlUtils.toString(latestUpdateResponse));
        }

        [Test]
        public void _130_putTransactionSet() {
            Kmehrmessage kmehrmessage = helper.createTransactionSetMessage(latestMedicationSchemeVersion);
            
            PutTransactionSetResponse putTransactionSet = hubService.putTransactionSet(kmehrmessage);
            
            XmlAsserter.assertSimilar(helper.expectedResponse("PutTransactionSet"), ConnectorXmlUtils.toString(putTransactionSet));
        }

        [Test]
        public void _140_getTransactionSet() {
            PatientIdType patientId = helper.createPatientIdType();
                    StringBuilder transactionSetIdBuilder = new StringBuilder()
                            .append("/subject/")
                            .append(HubConfigVitalink.PATIENT_NISS)
                            .append("/medication-scheme");
            
            
            GetTransactionSetResponse transactionResponse = hubService.getTransactionSet(patientId, helper.createTransactionBaseType(URI_TRANSACTION, transactionSetIdBuilder.toString()));

            XmlAsserter.assertSimilar(helper.expectedResponse("GetTransactionSet"), ConnectorXmlUtils.toString(transactionResponse));
        }

	    [Test]
	    public void _150_getPatientAudiTrail() {
	        SelectGetPatientAuditTrailType patientAudiTrail = new SelectGetPatientAuditTrailType();
	        patientAudiTrail.setBegindate(new org.joda.time.DateTime());
	        patientAudiTrail.setEnddate(new org.joda.time.DateTime());
        	patientAudiTrail.setHcparty(helper.createHcPartyIdProfessional());
        	patientAudiTrail.setPatient(helper.createPatientIdType());
	        patientAudiTrail.setSearchtype(LocalSearchType.LOCAL);
	        patientAudiTrail.setTransaction(helper.createTransactionBaseType(URI_TRANSACTION, transactionId));

	        GetPatientAuditTrailResponse getPatientAuditTrailResponse = hubService.getPatientAuditTrail(patientAudiTrail);

	        Assert.AreEqual("367", ((CDERROR) ((ErrorType) getPatientAuditTrailResponse.getAcknowledge().getErrors().get(0)).getCds().get(0)).getValue(), "Role [physician] should not be allowed to perform action");
	    }

        [Test]
	    public void _160_declareTransaction() {
	        KmehrHeaderDeclareTransaction kmehrHeader = new KmehrHeaderDeclareTransaction();
	        be.fgov.ehealth.hubservices.core.v3.FolderType folder = new be.fgov.ehealth.hubservices.core.v3.FolderType();
	        PatientIdType patient = helper.createPatientIdType();

	        TransactionSummaryType transaction = new TransactionSummaryType();
	        AuthorType author = helper.createAuthor();
	        transaction.setAuthor(author);
	        CDTRANSACTION cdTransaction = new CDTRANSACTION();
	        cdTransaction.setS(CDTRANSACTIONschemes.CD_TRANSACTION);
	        cdTransaction.setSV("1.0");
	        cdTransaction.setValue("sumehr");
	        transaction.getCds().add(cdTransaction);
	        transaction.setDate(new org.joda.time.DateTime());
	        transaction.getIds().add(helper.createMessageId(HubConfigCommon.MESSAGE_ID));
	        transaction.setIscomplete(true);
	        transaction.setIsvalidated(true);
	        transaction.setTime(new org.joda.time.DateTime());
	        transaction.setRecorddatetime(new org.joda.time.DateTime());

	        folder.setTransaction(transaction);
	        folder.setPatient(patient);
	        kmehrHeader.setFolder(folder);
	        
	        try {
               hubService.declareTransaction(kmehrHeader);
               Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
	    }
	    
	    [Test]
        public void _170_requestPublication() {
            try {
               hubService.requestPublication(helper.createPatientIdType(), helper.createTransactionWithPeriodType(), "");
               Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }
    
        [Test]
        public void _180_putHcParty() {
            try {
               hubService.putHCParty(helper.createHcPartyAdaptedType());
               Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }
    
        [Test]
        public void _190_getHcParty() {
            HCPartyIdType hcParty = helper.createHcPartyIdProfessional();
            
            try {
               hubService.getHCParty(hcParty);
               Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }
    
        [Test]
        public void _200_getHcPartyConsent() {
            HCPartyIdType hcParty = helper.createHcPartyIdProfessional();
            
   			try {
               hubService.getHCPartyConsent(hcParty);
               Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }
        
        [Test]
        public void _210_revokeHcPartyConsent() {
            ConsentHCPartyType consent = new ConsentHCPartyType();
            consent.setAuthor(helper.createAuthor());
            consent.setHcparty(helper.createHcPartyIdProfessional());
            consent.setRevokedate(new org.joda.time.DateTime());
            consent.setSigndate(new org.joda.time.DateTime());
    
            try {
               hubService.revokeHCPartyConsent(consent);
               Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }
	    
	    [Test]
        public void _220_revokeTherapeuticLink() {
            TherapeuticLinkType therapeuticLink = helper.createTherapeuticLinkType();
            therapeuticLink.setEnddate(new org.joda.time.DateTime());

            try {
               hubService.revokeTherapeuticLink(therapeuticLink);
               Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }

        [Test]
        public void _230_revokePatientConsent() {
            ConsentType consent = helper.createConsentType();
            consent.setRevokedate(new org.joda.time.DateTime());
            
            try {
               hubService.revokePatientConsent(consent);
               Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }
        
    
        [Test]
        public void _240_putAccessRight() {
            AccessRightType accessRight = new AccessRightType();
            CDACCESSRIGHT cdAccessRight = new CDACCESSRIGHT();
            cdAccessRight.setS(CDACCESSRIGHTschemes.CD_ACCESSRIGHT);
            cdAccessRight.setSV("1.0");
            cdAccessRight.setValue(CDACCESSRIGHTvalues.ALLOW);
            accessRight.setCd(cdAccessRight);
            be.fgov.ehealth.hubservices.core.v3.HcpartyType hcParty = new be.fgov.ehealth.hubservices.core.v3.HcpartyType();
            hcParty.getCds().add(helper.createCdHcPartyProfession());
            hcParty.getIds().add(helper.createIdHcPartyNihii());
            accessRight.setHcparty(hcParty);
            TransactionIdType transaction = helper.createTransactionIdType(transactionId);
            accessRight.setTransaction(transaction);
            
            try {
                hubService.putAccessRight(accessRight);
                Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }
    
        [Test]
        public void _250_getAccessRight() {
            TransactionIdType transaction = new TransactionIdType();
            IDKMEHR id = helper.createMessageId(HubConfigCommon.MESSAGE_ID);
            transaction.getIds().add(id);
            
            try {
               hubService.getAccessRight(transaction);
               Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }
    
       [Test]
        public void _260_revokeAccessRight() {
            SelectRevokeAccessRightType accessRight = new SelectRevokeAccessRightType();
            be.fgov.ehealth.hubservices.core.v3.HcpartyType hcParty = new be.fgov.ehealth.hubservices.core.v3.HcpartyType();
            hcParty.getCds().add(helper.createCdHcPartyProfession());
            hcParty.getIds().add(helper.createIdHcPartyNihii());
            accessRight.setHcparty(hcParty);
            accessRight.setTransaction(helper.createTransactionIdType(transactionId));
            
            try {
               hubService.revokeAccessRight(accessRight);
               Assert.Fail("Should throw unsupported error");
            } catch (TechnicalConnectorException e) {
               Assert.AreEqual("Unknown error occured : Not supported", e.getMessage());
            }
        }
	    
	    private void setLatestMedicationSchemeVersion(GetLatestUpdateResponse latestUpdateResponse) {
	    	java.util.List latestUpdates = latestUpdateResponse.getLatestupdatelist().getLatestupdates();
	    	for (int i = 0; i<latestUpdates.size(); i++) {
				Latestupdate latestupdate = (Latestupdate) latestUpdates.get(i);
                if ("medicationscheme".Equals(latestupdate.getCd().getValue())) {
					latestMedicationSchemeVersion = new Integer(latestupdate.getVersion()).intValue();
                }
            }
        }
	}

	
}
