package com.shin1ogawa.logic;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isIn;
import static org.junit.Assert.assertThat;

import java.io.IOException;
import java.net.HttpURLConnection;

import org.junit.Before;
import org.junit.Test;

import com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchRequest;
import com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse;
import com.shin1ogawa.logic.UrlFetchLogic;
import com.shin1ogawa.logic.UrlFetchLogic.Response;
import com.shin1ogawa.servicemock.UrlFetchServiceMock;

public class UrlFetchLogicTest extends AbstractLogicTest {
	@Before
	public void setUp() {
		super.setUp();
		getApiProxyLocal().addServiceMock(
				new UrlFetchServiceMock.AbstractUrlFetchServiceMock() {
					public URLFetchResponse fetch(URLFetchRequest request) {
						URLFetchResponse response = new URLFetchResponse();
						String url = request.getUrl();
						if (url.indexOf("/api/feed/public") >= 0) {
							response
									.setStatusCode(HttpURLConnection.HTTP_ACCEPTED);
							response.setContent("public feed!");
						} else if (url.indexOf("/api/feed/home") >= 0) {
							if (hasHeader(request, "Authorization")) {
								response
										.setStatusCode(HttpURLConnection.HTTP_OK);
								response.setContent("home feed!");
							} else {
								response
										.setStatusCode(HttpURLConnection.HTTP_UNAUTHORIZED);
								response.setContent("unauthorized!");
							}
						} else {
							response
									.setStatusCode(HttpURLConnection.HTTP_INTERNAL_ERROR);
							response.setContent("internal error!");
						}
						return response;
					}
				});
	}

	@Test
	public void testFriendFeed01() throws IOException {
		Response response = UrlFetchLogic.friendfeed("/api/feed/public");
		assertThat(response.responseCode, isIn(new Integer[] {
				HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_ACCEPTED }));
		String responseString = new String(response.responseBytes);
		assertThat(responseString, is("public feed!"));
	}

	@Test
	public void testFriendFeed02() throws IOException {
		Response response = UrlFetchLogic.friendfeed("/api/feed/home", "foo",
				"bar");
		assertThat(response.responseCode, is(HttpURLConnection.HTTP_OK));
		String responseString = new String(response.responseBytes);
		assertThat(responseString, is("home feed!"));
	}

	@Test
	public void testFriendFeed03() throws IOException {
		// 認証エラー
		Response response = UrlFetchLogic.friendfeed("/api/feed/home", "", "");
		assertThat(response.responseCode,
				is(HttpURLConnection.HTTP_UNAUTHORIZED));
		String responseString = new String(response.responseBytes);
		assertThat(responseString, is("unauthorized!"));
	}
}
