package com.avaya.zephyr.services.sample_services.CallableService.util;


import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.Mockito.when;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import com.avaya.collaboration.util.logger.Logger;
import com.avaya.zephyr.services.sample_services.CallableService.attributeReaders.ClusterAttributeReader;
import com.avaya.zephyr.services.sample_services.CallableService.attributeReaders.TrafficInterfaceAddressRetriever;
import com.avaya.zephyr.services.sample_services.CallableService.util.CallableServiceHttpUtil;

@PrepareForTest( {CallableServiceHttpUtil.class, CallableServiceUtil.class,
	URL.class})
@RunWith(PowerMockRunner.class)
public class CallableServiceHttpUtilTest {
	static final String AUDIO_FILE_DOES_NOT_EXIST = "DOES NOT EXIST";
	static final String HTTP_DELETE = "DELETE";
	
	CallableServiceHttpUtil callableServiceHttpUtil;
	
	@Mock
	ClusterAttributeReader clusterAttributeReader;
	
	@Mock
	TrafficInterfaceAddressRetriever trafficInterfaceAddressRetriever;
	
	@Mock
	CallableServiceUtil callableServiceUtil;
	
	@Mock
	Logger logger;
	
	@Mock
	URL url;
	
	@Mock
	HttpURLConnection httpURLConnection;
	
	InputStream inputStream;
	
	@Before
	public void setUp() throws Exception
	{
		PowerMockito.whenNew(CallableServiceUtil.class).
		withAnyArguments().thenReturn(callableServiceUtil);
		PowerMockito.whenNew(URL.class).
		withAnyArguments().thenReturn(url);
		when(url.openConnection()).thenReturn(httpURLConnection);
		when(logger.isFinerEnabled()).thenReturn(true);
		callableServiceHttpUtil = new CallableServiceHttpUtil(logger);
	}

	@Test
	public void requestPut() throws Exception
	{
		inputStream = IOUtils.toInputStream("");
		when(httpURLConnection.getInputStream()).thenReturn(inputStream);
		String output1 = callableServiceHttpUtil.requestPut("testname.wav");
		assertEquals(AUDIO_FILE_DOES_NOT_EXIST, output1);
		inputStream = IOUtils.toInputStream(HTTP_DELETE + '\n');
		when(httpURLConnection.getInputStream()).thenReturn(inputStream);
		String output2 = callableServiceHttpUtil.requestPut("testname.wav");
		assertEquals(HTTP_DELETE, output2);
	}

	@Test
	public void requestDelete()
	{
		int returnval = callableServiceHttpUtil.requestDelete("testname.wav");
		assertNotEquals(returnval, -1);
	}
}
