#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import urllib
import urlparse
import xbmcgui
import xbmcplugin
import xbmcaddon
import feedparser
import unicodedata
import resolveurl as urlresolver

my_addon = xbmcaddon.Addon()
PATH = my_addon.getAddonInfo('path')
IMG  = PATH + '/img/'

base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
args = urlparse.parse_qs(sys.argv[2][1:])

#xbmcplugin.setContent(addon_handle, 'movies')

def build_url(query):
    return base_url + '?' + urllib.urlencode(query)
	

mode = args.get('mode', None)

if mode is None:
	li = xbmcgui.ListItem('WeszloFM - Play Live', iconImage = IMG + 'weszlofm.jpg')   
	li.setProperty('fanart_image', '')  
	li.setProperty('IsPlayable', 'true')   
	url = build_url({'mode': 'stream', 'url': 'http://radio.weszlo.fm/s7d70a7895/listen', 'title': 'radio1'}) 
	xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)

	url = build_url({'mode': 'archiwum', 'foldername': 'Archiwum'})
	li = xbmcgui.ListItem('WeszloFM - Archiwum', iconImage='DefaultFolder.png')
	xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)
		
	xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'live': 
	li = xbmcgui.ListItem('WeszloFM', iconImage = IMG + 'weszlofm.jpg')   
	li.setProperty('fanart_image', '')  
	li.setProperty('IsPlayable', 'true')   
	url = build_url({'mode': 'stream', 'url': 'http://radio.weszlo.fm/s7d70a7895/listen', 'title': 'radio1'}) 
	xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)
   
	xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'stream':
	url = args['url'][0]
	play_item = xbmcgui.ListItem(path=url)
	xbmcplugin.setResolvedUrl(addon_handle, True, listitem=play_item)
	
	xbmcplugin.endOfDirectory(addon_handle)
	
elif mode[0] == 'archiwum':
	f = feedparser.parse('http://feeds.soundcloud.com/users/soundcloud:users:386530112/sounds.rss')
	for e in f['entries']:
		video_play_url = e.links[1].href
		url = build_url({'mode' :'play', 'playlink' : video_play_url})
		li = xbmcgui.ListItem(unicodedata.normalize('NFD', e.title).encode('ascii', 'ignore'), iconImage=e.image.href)
		li.setProperty('IsPlayable' , 'true')
		xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)
	xbmcplugin.endOfDirectory(addon_handle)
	

elif mode[0] == 'play':
	final_link = args['playlink'][0]
	play_item = xbmcgui.ListItem(path=final_link)
    # the list item is ready to be played by Kodi
	xbmcplugin.setResolvedUrl(addon_handle, True, listitem=play_item)
	xbmcplugin.endOfDirectory(addon_handle)