# Generate an RSS page.
# -*- mode: python; coding: utf-8 -*-
# Copyright © 2011, Translation Project.
# Mikel Olasagasti Uranga <mikel@olasagasti.info>, 2011.
# Erwin Poeze <erwin.poeze@gmail.com>, 2011.

import datetime
import PyRSS2Gen
import feedparser
import config

MAX_ITEMS = 50

def generate_po_rss(translator, pofile, percentage, domain, code):
	items = []
	url = "https://translationproject.org/PO-files/"+code+"/"+pofile

	# Generate the first item from the passed parameters.
	items.append(PyRSS2Gen.RSSItem(
		title = pofile,
		link = url,
		description = pofile+" has been updated to "+percentage+" by "+translator,
		guid = PyRSS2Gen.Guid(url),
		pubDate = datetime.datetime.utcnow()))

	# Open the current RSS file.
	d = feedparser.parse('%s/tp_po.xml' % config.feed_path)

	# Limit the number of entries for the new file.
	MAX = len(d['entries'])
	if MAX > MAX_ITEMS - 1:
		MAX = MAX_ITEMS - 1

	# Generate MAX items from the existing RSS file and append to first item,
	# but skip any items that have the same URL as the first one.
	for i in range(0, MAX):
		if d['entries'][i]['link'] == url:
			continue
		items.append(PyRSS2Gen.RSSItem(
			title = d['entries'][i]['title'],
			link = d['entries'][i]['link'],
			description = d['entries'][i]['description'],
			guid = PyRSS2Gen.Guid(d['entries'][i]['guid']),
			pubDate = d['entries'][i]['published']))

	# Generate the RSS file.
	rss = PyRSS2Gen.RSS2(
		title = "Translation Project RSS for PO files",
		link = "https://www.translationproject.org",
		description = "Latest translated domains",
		lastBuildDate = datetime.datetime.utcnow(),
		items = items)

	rss.write_xml(open('%s/tp_po.xml' % config.feed_path, 'w'), encoding = "utf-8")
