/*
 * Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services. 
 * All rights reserved. 
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met: 
 *     * Redistributions of source code must retain the above 
 *       copyright notice, this list of conditions and the following disclaimer. 
 *     * Redistributions in binary form must reproduce the above copyright 
 *       notice, this list of conditions and the following disclaimer in the documentation 
 *       and/or other materials provided with the distribution. 
 *     * Neither the name of the United States Government nor the 
 *       names of its contributors may be used to endorse or promote products 
 *       derived from this software without specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY 
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */
package gov.hhs.fha.nhinc.direct.edge.proxy;

import static org.junit.Assert.*;
import ihe.iti.xds_b._2007.DocumentRepositoryPortType;
import ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import gov.hhs.fha.nhinc.direct.DirectUnitTestUtil;
import gov.hhs.fha.nhinc.messaging.client.CONNECTClient;
import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;

import oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;

import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;

/**
 * @author mweaver
 *
 */
public class DirectEdgeProxySoapImplTest {

    private DirectEdgeProxy objectUnderTest = null;
    private DirectEdgeProxyObjectFactory factory = null;
    private CONNECTClient<DocumentRepositoryPortType> mockClient;

    /**
     * Setup for tests.
     */
    @Before
    public void setUp() {

        if (factory == null) {
            factory = new DirectEdgeProxyObjectFactory() {
                @Override
                public DirectEdgeProxy getDirectEdgeProxy() {
                    return new DirectEdgeProxySoapImpl();
                }
            };
        }

        if (objectUnderTest == null) {
            objectUnderTest = factory.getDirectEdgeProxy();
        }
    }

    /**
     * Tests if the instance is actually a soap impl as opposed to a java, smtp, etc.
     */
    @Test
    public void testIsSoapEdge() {
        if (!(objectUnderTest instanceof DirectEdgeProxySoapImpl)) {
            fail("objectUnderTest is not an instance of DirectEdgeProxySoapImpl.");
        }
    }

    /**
     * This test requires a mock or otherwise endpoint stood up at the url defined for the directedgesoap entry in
     * internalConnectionInfo.xml.
     * 
     * @throws MessagingException
     */
    @Test
    @Ignore
    public void testSend() throws MessagingException {
        MimeMessage message = new MimeMessage(null, IOUtils.toInputStream(DirectUnitTestUtil
                .getFileAsString("Example_A.txt")));
        RegistryResponseType resp = objectUnderTest.provideAndRegisterDocumentSetB(message);

        assertTrue(resp.getStatus().contains("Success"));
    }

    /**
     * Tests the DirectEdgeProxySoapImpl class with a mocked up CONNECTClient. This test will ensure that the url can
     * be looked up successfully, as well as the transformation from XDM to XDR.
     * 
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @Test
    public void testSendWithMockedObjects() throws Exception {
        System.out.println("NHINC_PROPERTIES_DIR: " + System.getenv(NhincConstants.NHINC_PROPERTIES_DIR));
        mockClient = mock(CONNECTClient.class);
        when(
                mockClient.invokePort(eq(DocumentRepositoryPortType.class),
                        eq("documentRepositoryProvideAndRegisterDocumentSetB"),
                        any(ProvideAndRegisterDocumentSetRequestType.class))).thenReturn(getSuccessResponse());

        MimeMessage message = new MimeMessage(null, IOUtils.toInputStream(DirectUnitTestUtil
                .getFileAsString("Example_A.txt")));
        objectUnderTest = getProxyWithMockClient();
        RegistryResponseType resp = objectUnderTest.provideAndRegisterDocumentSetB(message);

        assertTrue(resp.getStatus().contains("Success"));
    }

    /**
     * @return an instance of DirectEdgeProxySoapImpl with a mocked up CONNECTClient.
     */
    private DirectEdgeProxySoapImpl getProxyWithMockClient() {
        return new DirectEdgeProxySoapImpl() {
            @Override
            protected CONNECTClient<DocumentRepositoryPortType> getClient(
                    ServicePortDescriptor<DocumentRepositoryPortType> portDescriptor, String url) {
                return mockClient;
            }
        };
    }
    
    /**
     * @return a RegistryResponseType with a status of success.
     */
    private RegistryResponseType getSuccessResponse() {
        RegistryResponseType resp = new RegistryResponseType();
        resp.setStatus(NhincConstants.NHINC_ADHOC_QUERY_SUCCESS_RESPONSE);
        return resp;
    }

}

@@ -2199,16 +2199,80 @@
 nstants;
+%0Aimport gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;
 %0A%0Aimport
@@ -2630,16 +2630,17 @@
 eaver%0A *
+ 
 %0A */%0Apub
@@ -2854,16 +2854,195 @@
 kClient;
+%0A    private WebServiceProxyHelper mockWebServiceProxyHelper = mock(WebServiceProxyHelper.class);%0A    private String endpointUrl = %22http://localhost:8080/DirectEdgeProxySoapImpl%22;
 %0A%0A    /*
@@ -4538,65 +4538,15 @@
  the
- url can%0A     * be looked up successfully, as well as the
+%0A     *
  tra
@@ -4572,16 +4572,31 @@
 M to XDR
+ was successful
 .%0A     *
@@ -5174,16 +5174,157 @@
 onse());
+%0A        when(mockWebServiceProxyHelper.getAdapterEndPointFromConnectionManager(any(String.class))).thenReturn(%0A                endpointUrl);
 %0A%0A      
@@ -6123,32 +6123,195 @@
 t;%0A            %7D
+%0A%0A            @Override%0A            protected WebServiceProxyHelper createWebServiceProxyHelper() %7B%0A                return mockWebServiceProxyHelper;%0A            %7D
 %0A        %7D;%0A    
@@ -6312,20 +6312,16 @@
 ;%0A    %7D%0A
-    
 %0A    /**

refactor of soap edge unit test to better isolate direct edge soap proxy impl