package com.shin1ogawa.logic;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

public class UrlFetchLogic {

	public static Response friendfeed(String method) throws IOException {
		return friendfeed(method, null, null);
	}

	public static Response friendfeed(String method, String nickname,
			String remoteKey) throws IOException {
		String urlString = "https://friendfeed.com" + method + "?format=xml";
		URL url = new URL(urlString);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");
		String authorizationString = "";
		if (!StringUtils.isEmpty(nickname) && !StringUtils.isEmpty(remoteKey)) {
			// basic authentication
			authorizationString = new String(Base64.encodeBase64((nickname
					+ ":" + remoteKey).getBytes()));
			connection.setRequestProperty("Authorization", "basic "
					+ authorizationString);
		}
		int responseCode = connection.getResponseCode();
		int contentLength = connection.getContentLength();
		ByteArrayOutputStream out = new ByteArrayOutputStream(contentLength);
		InputStream input = connection.getInputStream();
		int length = -1;
		byte[] responseBytes = new byte[256];
		while ((length = input.read(responseBytes)) != -1) {
			out.write(responseBytes, 0, length);
		}
		return new Response(responseCode, out.toByteArray());
	}

	public static class Response {
		public final int responseCode;
		public final byte[] responseBytes;

		public Response(int responseCode, byte[] responseBytes) {
			this.responseCode = responseCode;
			this.responseBytes = responseBytes;
		}
	}
}
