#!/usr/bin/python
# -*- coding: latin-1 -*-
# -----------------------------------------------
# Initalization of modules
# uses objects "tux" and "tss"
# -----------------------------------------------
import sys
import urllib2
sys.path.append('/opt/tuxdroid/api/python')
from tux import *
from xml.dom import minidom as dom

""" Create the dictionaries for the news feeds """

feeds = { "World" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/world/rss.xml",
"UK": "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/uk/rss.xml",
"England" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/england/rss.xml",
"Northern Ireland" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/northern_ireland/rss.xml",
"Scotland" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/scotland/rss.xml",
"Wales" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/wales/rss.xml",
"Business" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/business/rss.xml",
"Politics" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/uk_politics/rss.xml",
"Health" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/health/rss.xml",
"Education" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/education/rss.xml",
"Science / Nature" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/sci/tech/rss.xml",
"Technology" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/technology/rss.xml",
"Entertainment" : "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/entertainment/rss.xml"
}
""" Limiting variables """
maxItems = 2

def printFeeds ():
	print "Current feeds"
	Ks = feeds.keys()
	for key in Ks:
		print key

def fetchPage(url):
	a = urllib2.urlopen(url)
	return ''.join(a.readlines())
 
def extract(page,selection):
	a = dom.parseString(page)
	tux.sys.wait(0.4)
	tux.tts.speak("News for "+selection)
	tux.sys.wait(0.5)
	item = a.getElementsByTagName('item')
	counter = 0
	for i in item:
		if counter < maxItems:
			if i.hasChildNodes() == True:
				t = i.getElementsByTagName('title')[0].firstChild.wholeText
				l = i.getElementsByTagName('link')[0].firstChild.wholeText
				d = i.getElementsByTagName('description')[0].firstChild.wholeText
				tux.tts.speak(t)
				tux.sys.wait(0.3)
				tux.tts.speak(d)
				tux.sys.wait(0.3)
				counter=counter+1
	tux.tts.speak("End of the news for "+selection)

""" Ask for users selection area """
# Show feeds available
printFeeds()
# Get users selection
selection = raw_input('Enter your selection:')    
# Select the feed
rssUrl = feeds[selection]
# Fetch feed contents
page = fetchPage(rssUrl)
# Process it
returnednews = extract(page,selection)
tux.disconnect_from_daemon()
# -----------------------------------------------------------------------------
# End of your script
# -----------------------------------------------------------------------------
tux.destroy()
