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.api.urlfetch.URLFetchServicePb.URLFetchRequest.Header;
import com.google.appengine.tools.development.LocalServiceContext;
import com.google.apphosting.api.ApiProxy.Environment;

public interface UrlFetchServiceMock extends ServiceMock {

	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 byte[] makeSyncCall(Environment environment, String packageName,
				String methodName, byte[] requestBytes) {
			if (methodName.equalsIgnoreCase("fetch")) {
				URLFetchRequest fetchRequest = new URLFetchRequest();
				fetchRequest.parseFrom(requestBytes);
				URLFetchResponse fetchResponse = fetch(fetchRequest);
				int length = fetchResponse.getContentAsBytes().length;
				fetchResponse.addHeader(new URLFetchResponse.Header().setKey(
						"content-length").setValue(String.valueOf(length)));
				return fetchResponse.toByteArray();
			} else {
				throw new UnsupportedOperationException(methodName);
			}
		}

		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;
		}

		/**
		 * @param request
		 * @param key
		 * @return 指定されたキーに対応する{@link Header}.
		 * 		キーに対応する{@link Header}が存在しない場合は{@code null}を返す。
		 */
		public static Header getHeader(URLFetchRequest request, String key) {
			int index = 0;
			try {
				while (true) {
					if (request.getHeader(index).getKey().equals(key)) {
						return request.getHeader(index);
					}
					index++;
				}
			} catch (Exception ex) {
				//
			}
			return null;
		}
	}
}
