#!/usr/bin/python
import gi
import time
import xmltodict
import requests
gi.require_version('Notify', '0.7')
from gi.repository import Notify
from xml.etree import ElementTree as ET

Notify.init("RSS Notifier")

LAST_LIST = []

def getXmlObjectFrom(url):
	global LAST_XML

	rssstring = requests.get(url)
	tree = xmltodict.parse(rssstring.text)
	rsstree = tree.get("rss", None)
	channeltree = rsstree.get("channel", None)
#	for cv in list(channeltree.values()):
#		print("-------\n%s\n------------------------\n" % (cv))
	return channeltree

def parseKLXml(channel):
	notes = []

	chandesc = channel.get("description", "N/A")
#	print("-------\n ChanDesc: %s\n--\n" % (chandesc))
#	print("-------\n Chan: %s\n--\n" % (channel))
#	values = channel.values()
#	keys = channel.keys()
#	print("-------\n values: %s\n--\n" % (values))
#	print("-------\n keyss: %s\n--\n" % (keys))

	itemlist = channel.get('item')

	global LAST_LIST

	for itemobj in itemlist:

		if itemobj in LAST_LIST:
			continue

		category = itemobj.get("category", "N/A")
		link     = itemobj.get("link", None)
		ts       = itemobj.get("pubDate", "N/A")
		title    = itemobj.get("title", "N/A")
		body     = itemobj.get("description", "N/A")
#		newsbody = None
#		if link:
#			newsbody = requests.get(link).text
#		if newsbody:
#			body     = body + "\n" + newsbody[0:100]
#			body     = body + " ..."
		linkstr  = "\n<a href=\"%s\">Link</a>" % (link)
		body     = body + linkstr
		sTitle   = "[" + ts + "] " + chandesc + "/" + category + ": " + title
#		print("%s: %s\n" %(sTitle, body))
		note     = Notify.Notification.new(sTitle, body, "dialog-information")
		notes.append(note)

	LAST_LIST = itemlist
		
			
	return notes

while 1:

	noteobjkl = getXmlObjectFrom("https://feeds.kauppalehti.fi/rss/main")

	noteskl = parseKLXml(noteobjkl)

	noteobjka = getXmlObjectFrom("https://feeds.kauppalehti.fi/rss/main")

	noteska = parseKLXml(noteobjka)

	for n in noteskl:
		time.sleep(10)
		n.show()

	for n in noteska:
		time.sleep(10)
		n.show()

	time.sleep(50)
