/*
 * Created by SharpDevelop.
 * User: EH058
 * Date: 11/06/2014
 * Time: 10:55
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using ikvm.extensions;
using NUnit.Framework;
using java.io;
using org.w3._2005._05.xmlmime;
using be.ehealth.business.mycarenetcommons.builders;
using be.ehealth.business.mycarenetcommons.builders.impl;
using be.ehealth.business.mycarenetcommons.domain;
using be.ehealth.business.mycarenetcommons.exception;
using be.ehealth.businessconnector.registration.builder;
using be.ehealth.businessconnector.registration.session;
using be.ehealth.technicalconnector.config.util;
using be.ehealth.technicalconnector.exception;
using be.ehealth.technicalconnector.session;
using be.ehealth.technicalconnector.utils;
using be.fgov.ehealth.mycarenet.registration.protocol.v1;
using be.fgov.ehealth.technicalconnector.tests.session;
using be.fgov.ehealth.technicalconnector.tests.utils;

namespace be.ehealth.businessconnector.registration.session
{
    /// <summary>
    /// Description of RegistrationIntegrationTest.
    /// </summary>
    [TestFixture]
    public class RegistrationIntegrationTest
    {

    [SetUp]
    public static void setupsession()  {
        System.Console.WriteLine("Start SetUp");
        
        SessionInitializer.init(".\\be.ehealth.businessconnector.registration.test.properties", SupportedLanguages.NET.getAbbreviation());
        System.Console.WriteLine("End SetUp");
    }

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

     [Test]
    [Ignore("OA not ready")]
    public void registerOA100Test()  {
        testOa("100");
    }

     [Test]
    public void registerOA300Test()  {
        testOa("300");
    }

     [Test]
    // @Ignore
    public void registerOA500Test()  {
        testOa("500");
    }

     [Test]
    public void registerOA600Test()  {
        testOa("600");
    }

     [Test]
     [Ignore("OA not ready")]
    public void registerOA900Test()  {
        testOa("900");
    }

     [Test]
    public void failHash()  {
        try {
            RegisterToMycarenetServiceResponse response = getResponse("300");

            ResponseBuilder responseBuilder = ResponseBuilderFactory.getResponseBuilder();
            response.getReturn().getDetail().setHashValue("fail".getBytes());
            responseBuilder.getResponse(response);
            Assert.Fail("the invalid hash should have been detected!");
            
        } catch (InvalidBlobContentConnectorException iBlob) {
            Assert.AreEqual(InvalidBlobContentConnectorExceptionValues.HASH_VALUES_DIFFERENT.getErrorCode(), iBlob.getErrorCode()); 
        }
    }

     [Test]
    public void failXades()  {
        try {
            RegisterToMycarenetServiceResponse response = getResponse("300");

            ResponseBuilder responseBuilder = ResponseBuilderFactory.getResponseBuilder();
            Base64Binary binary = new Base64Binary();
            binary.setContentType("txt/xml");
            binary.setValue("<RegisterToMycarenetServiceResponse/>".getBytes());
            response.getReturn().setXadesT(binary);
            responseBuilder.getResponse(response);
            Assert.Fail("the invalid xades should have been detected!");

        } catch (InvalidBlobContentConnectorException iBlob) {
            Assert.AreEqual(InvalidBlobContentConnectorExceptionValues.XADESVALUES_DIFFERENT.getErrorCode(), iBlob.getErrorCode()); 
        }
    }


    /**
     * @param oa
     */
    private void testOa(String oa)  {

        RegisterToMycarenetServiceResponse response = getResponse(oa);

        ResponseBuilder responseBuilder = ResponseBuilderFactory.getResponseBuilder();
        try {
            String xmlValue = responseBuilder.getResponse(response);
            Assert.NotNull(xmlValue);
            Assert.IsFalse(xmlValue.contains("status=\"ERROR\"") && !xmlValue.contains(":DetailCode>168</"),"response indicates error : \n " + xmlValue);
        } catch (InvalidBlobContentConnectorException e) {
            String xmlValue = responseBuilder.getResponse(response, false);
            Assert.Fail("validation error on following response\n" + xmlValue);
        }
    }



    /**
     * @param oa
     * @return
     * @throws TechnicalConnectorException
     * @throws InvalidBlobContentConnectorException
     * @throws ConnectorException
     */
    private RegisterToMycarenetServiceResponse getResponse(String oa) {
        RequestBuilder mapper = RegistrationRequestBuilderFactory.getRequestObjectBuilder();
        CommonInput commonInput = RequestBuilderFactory.getCommonBuilder("mcn.registration").createCommonInput(ConfigUtil.retrievePackageInfo("mcn.registration"), true, "");
        // Blob blob = RequestBuilderFactory.getBlobBuilder("mcn.registration").build("TEST".getBytes());
        InputStream businessXmlContentStream = ConnectorIOUtils.getResourceAsStream(".\\examples\\DetailContentOfExamplesRegistrationRequest.xml");
        String testFileContent = System.Text.Encoding.UTF8.GetString(ConnectorIOUtils.getBytes(businessXmlContentStream));
        testFileContent = testFileContent.replaceAll("replaceWithDateYYYY-MM-DD", new org.joda.time.DateTime().toString("YYYY-MM-dd"));
        testFileContent = testFileContent.replaceAll("replaceWithNihiiNumber", SessionUtil.getNihii11());
        Blob blob = RequestBuilderFactory.getBlobBuilder("mcn.registration").build(testFileContent.getBytes());
        RegisterToMycarenetServiceRequest request = mapper.buildRegisterToMycarenetRequest(commonInput, getRouting(oa), blob, null);
        RegistrationSession session = RegistrationSessionFactory.getRegistrationSession();

        RegisterToMycarenetServiceResponse response = session.registerToMycarenetService(request);
        return response;
    }


    private static Routing getRouting(String oa) {
        CareReceiverId careReceiver = new CareReceiverId(null);
        careReceiver.setMutuality(oa);
        // GregorianCalendar date = new GregorianCalendar(2014, 3, 25);
        // new DateTime(date.getTime())
        return new Routing(careReceiver, new org.joda.time.DateTime());
    }
    }
}
