package com.shin1ogawa.servicemock;

import java.util.Map;

import com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchRequest;
import com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse;
import com.google.appengine.tools.development.LocalRpcService;
import com.google.appengine.tools.development.LocalServiceContext;

public interface UrlFetchServiceMock extends LocalRpcService {

	URLFetchResponse fetch(Status status, URLFetchRequest request);

	URLFetchResponse fetch(URLFetchRequest request);

	abstract class AbstractUrlFetchServiceMock implements UrlFetchServiceMock {
		public String getPackage() {
			return "urlfetch";
		}

		@SuppressWarnings("unchecked")
		public void init(LocalServiceContext localservicecontext, Map map) {
		}

		public void start() {
		}

		public void stop() {
		}

		public URLFetchResponse fetch(Status status, URLFetchRequest request) {
			URLFetchResponse response = fetch(request);
			int length = response.getContentAsBytes().length;
			response.addHeader(new URLFetchResponse.Header().setKey(
					"content-length").setValue(String.valueOf(length)));
			return response;
		}

		public static boolean hasHeader(URLFetchRequest request, String key) {
			int index = 0;
			try {
				while (true) {
					if (request.getHeader(index).getKey().equals(key)) {
						return true;
					}
					index++;
				}
			} catch (NullPointerException ex) {
				// 
			}
			return false;
		}

		public static String getHeaderValue(URLFetchRequest request, String key) {
			int index = 0;
			try {
				while (true) {
					if (request.getHeader(index).getKey().equals(key)) {
						return request.getHeader(index).getValue();
					}
					index++;
				}
			} catch (Exception ex) {
				//
			}
			return null;
		}
	}
}
