

package gov.va.med.cds.client;


import gov.va.med.cds.client.webservice.ClinicalDataServiceSynchronousInterface;
import gov.va.med.cds.client.webservice.ClinicalDataServiceSynchronousInterfaceLocator;
import gov.va.med.cds.exception.ClinicalDataServiceCreateException;
import gov.va.med.cds.registry.JAXRUtility;
import gov.va.med.cds.util.EndpointResolver;

import java.net.MalformedURLException;
import java.net.URL;


public class ClinicalDataServiceFactory
{

    private String serviceBindingId = null;

    private JAXRUtility jaxrHelper = null;

    private EndpointResolver endpointResolver = null;


    public synchronized ClinicalDataServiceSynchronousInterface create( )
    {
        try
        {
            return getBusinessDelegate();
        }
        catch ( Exception ex )
        {
            throw new ClinicalDataServiceCreateException( "Could not create CDS web service client.", ex );
        }
    }


    private ClinicalDataServiceSynchronousInterface getBusinessDelegate( )
    {
        try
        {

            URL endpoint = new URL( endpointResolver.resolve( serviceBindingId ) );

            String endPointAsString = endpoint.toString();

            if ( null != endPointAsString && !endPointAsString.contains( "?" ) )
            {
                try
                {
                    endpoint = new java.net.URL( endPointAsString + "?wsdl" );

                }
                catch ( MalformedURLException e )
                {
                    throw new Exception( e );
                }
            }

            ClinicalDataServiceSynchronousInterfaceLocator locator = new ClinicalDataServiceSynchronousInterfaceLocator( endpoint );

            ClinicalDataServiceSynchronousInterface port = locator.getClinicalDataServiceSynchronousInterfaceHttpPort();

            return port;

        }
        catch ( Exception e )
        {
            throw new ClinicalDataServiceCreateException( "Error find ing CDS service in end point look-up registry", e );
        }
    }


    public void setServiceBindingId( String serviceBindingId )
    {
        this.serviceBindingId = serviceBindingId;
    }


    public void setEndpointResolver( EndpointResolver endpointResolver )
    {
        this.endpointResolver = endpointResolver;
    }


    public void setJaxrHelper( JAXRUtility jaxrHelper )
    {
        this.jaxrHelper = jaxrHelper;
    }
}
