#!/usr/bin/env python

from __future__ import with_statement
import urllib2
import simplejson
import dbus
import datetime
import sys

LAST_RUN_DATE_TIME_FILE = '/home/user/Event Feed/examples/YouTube/last_run.txt' # File to read/write serialized date/time when script was last run.
SCRIPT_FILE = '/home/user/Event\ Feed/examples/YouTube/get_youtube_videos' # Path to the script.

def get_youtube_videos(query):
	""" Retrieve YouTube videos and populate the Hildon Event Feed
	
	Usage: get_youtube_videos [query]
    """
    
	query = query.strip().replace(' ', '+')
	video_feed = 'http://gdata.youtube.com/feeds/api/videos?v=2.1&max-results=20&alt=json&orderby=published&q='
	video_fields = 'entry(media:group(media:title,media:thumbnail,media:description,media:credit,yt:uploaded,yt:videoid))'
	
	source_name = 'youtube_example' # Identifies the source of the events. Must be unique to the source.
	source_display_name = 'YouTube' # Display name for the source in the event feed UI.
	icon = '/home/user/Event Feed/examples/YouTube/youtube_icon.png' # Icon to be displayed in the event feed UI.
	action = 'dbus:system com.nokia.osso_browser /com/nokia/osso_browser/request com.nokia.osso_browser load_url' # This will be called when the user taps on an item in the event feed. In this example, the video url is opened in the browser.
	refresh_action = 'exec python %s %s' % (SCRIPT_FILE, query) # This will be called when the user presses the 'Refresh' button in the event feed UI.
	
	bus = dbus.SessionBus()
	iface = dbus.Interface(bus.get_object('com.maemo.eventFeed', '/'), 'com.maemo.eventFeed') # Connect to event feed dbus object
	iface.addRefreshAction(source_name, refresh_action) # Add a refresh action to the event feed.
	
	last_run = script_last_run() # Time when script was last run. Will be used to check against the date/time of each video in the feed.
	
	result = urllib2.urlopen('%s%s&fields=%s' % (video_feed, query, video_fields)).read()
	json_result = simplejson.loads(result)
	
	try:
		result = json_result['feed']
		videos = result['entry']
	except:
		videos = []
		print 'Error retrieving video feed'
	
	for video in videos:
		try:
			group = video['media$group']
			video_id = group['yt$videoid']['$t']
			title = group['media$title']['$t']
			description = group['media$description']['$t']
			thumbnail = group['media$thumbnail'][3]['url']
			thumbnail2 = group['media$thumbnail'][4]['url']
			uploader = group['media$credit'][0]['$t']
			upload_date = group['yt$uploaded']['$t']
			
			try:
				item_date_time = datetime.datetime.strptime(upload_date[0: upload_date.find('.')], '%Y-%m-%dT%H:%M:%S')
			except:
				print 'Cannot parse item date/time. Using default'
				item_date_time = datetime.datetime.min
			
			if item_date_time > last_run:
				print iface.addEvent(source_name, source_display_name, icon, title, description, [thumbnail, thumbnail2], uploader, upload_date, '%s http://www.youtube.com/watch?v=%s' % (action, video_id))
		
		except:
			print 'Error processing video item'
			
	set_script_last_run(datetime.datetime.now().strftime('%Y, %m, %d, %H, %M, %S'))

def script_last_run():
	""" Read serialized date/time from last_run.txt. """
	
	date_time_string = ''
	last_run = datetime.datetime.min
	
	try:
		with open(LAST_RUN_DATE_TIME_FILE, 'r') as file:
			date_time_string = file.read()
			file.close()
			
		if date_time_string != '':
			try:
				last_run = datetime.datetime.strptime(date_time_string, '%Y, %m, %d, %H, %M, %S')
			except:
				print 'Saved date/time in incorrect format. Using default'
				
	except IOError:
		print 'Cannot read date/time from file. Using default.'
					
	return last_run
	
def set_script_last_run(date_time_string):
	""" Serialize the date/time the script was last run to last_run.txt. """

	try:
		with open(LAST_RUN_DATE_TIME_FILE, 'w') as file:
			file.write(unicode(date_time_string))
			file.close()
	except IOError:
		print 'Cannot write date/time to file'

if __name__ == '__main__':
	if len(sys.argv) == 2:
		sys.exit(get_youtube_videos(sys.argv[1]))
	else:
		print 'Usage: get_youtube_videos [query]'