package gov.va.med.mpn.extract;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.core.Response;

import org.apache.cxf.endpoint.Server;
import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
import org.apache.cxf.transport.local.LocalConduit;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/applicationContext-test.xml" })
public class ExtractServiceTest extends Assert {
	private final static String ENDPOINT_ADDRESS = "local://extracts";
	private static Server server;


	@BeforeClass
	public static void initialize() throws Exception {
	     startServer();
	}

	private static void startServer() throws Exception {
	     JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
	     sf.setResourceClasses(ExtractService.class);

	     List<Object> providers = new ArrayList<Object>();
	     // add custom providers if any
	     sf.setProviders(providers);

	     sf.setResourceProvider(ExtractService.class,
	                            new SingletonResourceProvider(new ExtractService(), true));
	     sf.setAddress(ENDPOINT_ADDRESS);

	     server = sf.create();
	}

	@AfterClass
	public static void destroy() throws Exception {
	   server.stop();
	   server.destroy();
	}

/*	@Test
	public void testGetExtractClientDirectDispatch() {
	WebClient client = WebClient.create(ENDPOINT_ADDRESS);
	WebClient.getConfig(client).getRequestContext().put(LocalConduit.DIRECT_DISPATCH, Boolean.TRUE);

	 client.accept("text/xml");
	 client.path("asciiservice/extract/123");
	 Response  t = client.get();
	 String p = t.getEntity().toString();

	 t.getStatus();
	}	*/

	@Test
	public void testAsciiExtractTest() {
	WebClient client = WebClient.create(ENDPOINT_ADDRESS);
	WebClient.getConfig(client).getRequestContext().put(LocalConduit.DIRECT_DISPATCH, Boolean.TRUE);
	 InputStream strem = null;
	 client.accept("text/xml");
	 client.path("asciiservice/asciiextract");
	 client.query("form", "vba-21-0960a-3-are");
	 try {
		 strem = this.getClass().getResourceAsStream("/hypertension_dbq.xml");
		 assertNotNull("File Stream cannot be null", strem);
		 String myResource = IOUtils.toString(strem);
		 assertNotNull("Metadata cannot be null", myResource);
		 Response  t = client.post(myResource);

		 assertTrue("Status should be 200", t.getStatus() == 200);
		 strem.close();

		} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();

	}

	}



}
