package de.jottyfan.camporganizer.module.rss;

import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import jakarta.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedOutput;

/**
 *
 * @author jotty
 *
 */
@Service
public class RssService {
	private static final Logger LOGGER = LogManager.getLogger(RssService.class);

	@Autowired
	private RssRepository repository;

	/**
	 * get the recipient's rss feed
	 *
	 * @param recipientCode the code for the feed
	 * @param response      the http servlet response
	 * @return the list of rss beans; an empty list at least
	 */
	public void getRss(String recipientCode, HttpServletResponse response) {
		List<RssBean> beans = new ArrayList<>();
		if (recipientCode != null) {
			beans = repository.getRss(recipientCode);
		} else {
			RssBean bean = new RssBean(null);
			bean.setPubdate(LocalDateTime.now());
			bean.setMessage("Dieser Feed ist nicht mehr aktuell. Bitte gib einen recipientCode an.");
			beans.add(bean);
		}
		SyndFeed feed = new RssModel().getRss(beans);
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/rss+xml");
		response.setHeader("Content-Disposition", "attachment; filename=\"onkelwernerfreizeiten.de.xml\"");
		try {
			PrintWriter writer = response.getWriter();
			new SyndFeedOutput().output(feed, writer);
			writer.flush();
			response.flushBuffer();
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}
}
