package tetest.calendar.groupQuestion;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class SecondServlet extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");

		PrintWriter out = resp.getWriter();

		String oneTimeUseToken = AuthSubUtil.getTokenFromReply(req.getQueryString());
		if (oneTimeUseToken != null) {
			try {
				String sessionToken = AuthSubUtil.exchangeForSessionToken(oneTimeUseToken, null);
				CalendarService calendarSerice = new CalendarService("some-app-name");
				calendarSerice.setAuthSubToken(sessionToken, null);
				URL feedUrl = new URL("http://www.google.com/calendar/feeds/default/private/full");
				CalendarQuery calendarQuery = new CalendarQuery(feedUrl);

				GregorianCalendar now_day = new GregorianCalendar();

				calendarQuery.setMinimumStartTime(new DateTime(now_day.getTime()));
				calendarQuery.setMaximumStartTime(new DateTime(now_day.getTime()));

				CalendarEventFeed resultFeed = calendarSerice.query(calendarQuery, CalendarEventFeed.class);

				out.println("Ok");
			} catch (AuthenticationException e) {
				out.println("err" + e.toString());
			} catch (GeneralSecurityException e) {
				out.println("err" + e.toString());
			} catch (ServiceException e) {
				out.println("err" + e.toString());			}
		}
	}

}
