package org.jerrymouse.chineseCalendar.view;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jerrymouse.chineseCalendar.model.atom.BirthdayEntity;
import org.jerrymouse.chineseCalendar.model.birthday.Birthday;
import org.jerrymouse.chineseCalendar.model.birthday.PeriodUpdater;
import org.jerrymouse.chineseCalendar.service.AtomService;
import org.jerrymouse.chineseCalendar.service.BirthdayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;

@Controller
public class FeedView {
	Log logger = LogFactory.getLog(FeedView.class);
	@Autowired
	AtomService atomService;

	@Autowired
	BirthdayService birthdayService;

	@Autowired
	PeriodUpdater periodUpdater;

	@RequestMapping
	public void listfeed(String data, HttpServletResponse response) {
		SyndFeed feed = creatFeed(data);
		SyndFeedOutput output = new SyndFeedOutput();

		response.setDateHeader("Last-Modified",
				periodUpdater.getThisWeek().begin.getTime().getTime());
		response.setHeader("Cache-Control", "max-age=86400, must-revalidate");
		response.setContentType("application/xml+atom;charset=utf-8");
		try {
			output.output(feed, response.getWriter());
		} catch (FeedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public SyndFeed creatFeed(String data) {
		List<Birthday> birthdays = birthdayService.decode(data);
		List<BirthdayEntity> birthdayEntitys = birthdayService
				.calculateNextTwoWeeks(birthdays);
		return atomService.creatWeekFeed(periodUpdater.getThisWeek().begin,
				birthdayEntitys, birthdays);
	}
}
