package com.shin1ogawa.servlet;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shin1ogawa.logic.UrlFetchLogic;
import com.shin1ogawa.logic.UrlFetchLogic.Response;

@SuppressWarnings("serial")
public class IndexServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		final String method = req.getParameter("method");
		final String nickname = req.getParameter("nickname");
		final String remoteKey = req.getParameter("remoteKey");

		Response friendfeed = UrlFetchLogic.friendfeed(method, nickname,
				remoteKey);

		resp.getWriter().println("<html><body>");
		resp.getWriter().println("<h1>" + method + "</h1>");
		resp.getWriter().println(
				"<p>response code=" + friendfeed.responseCode + "</p>");
		System.out.println("Read start.");
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new ByteArrayInputStream(friendfeed.responseBytes)));
		String line = null;
		resp.getWriter().println("<p>");
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
			resp.getWriter().println(line + "<br />");
		}
		resp.getWriter().println("</p>");
		resp.getWriter().println("</body></html>");
	}
}
