# TODO/FIXME: Encode GRILOHTTPD + args['url'][0] to handle URL with '/' in filename.
#             Get .. working and allow grilohttpd to serve twice w/o restart

import os
import subprocess
import sys
import time
import urllib
import urlparse
import xbmcaddon
import xbmcgui
import xbmcplugin
import requests
from bs4 import BeautifulSoup

GRILOHTTPD = 'http://localhost:8080/'

def build_url(query):
    base_url = sys.argv[0]
    try:
        str = base_url + '?' + urllib.urlencode(query)
    except UnicodeEncodeError:
        str = ''
    return str
    
def get_page(url):
    return BeautifulSoup(requests.get(url).text, 'html.parser')

def get_page_retry(url):
    while (True):
        try:
            text = get_page(url)
            break
        except:
            time.sleep(1)
    return text
    
def parse_page(page):
    links = {}
    for link in page.find_all('a'):
        links[link.string] = link['href']
    return links
    
def build_link_list(links):
    link_list = []
    for name in links:
        li = xbmcgui.ListItem(label=name)
        if links[name][-1] == '/':
            mode = 'dir'
            isFolder = True
        else:
            mode = 'stream'
            isFolder = False
            li.setProperty('IsPlayable', 'true')
        url = build_url({'mode': mode, 'url': links[name], 'title': name})
        link_list.append((url, li, isFolder))
        xbmc.log(url, level=xbmc.LOGERROR)
    xbmcplugin.addDirectoryItems(addon_handle, link_list, len(link_list))
    xbmcplugin.setContent(addon_handle, 'songs')
    xbmcplugin.endOfDirectory(addon_handle)
    
def play_song(url):
    play_item = xbmcgui.ListItem(path=url)
    xbmcplugin.setResolvedUrl(addon_handle, True, listitem=play_item)
    
def main():
    args = urlparse.parse_qs(sys.argv[2][1:])
    mode = args.get('mode', None)
    
    if mode is None:
        path = xbmcaddon.Addon().getAddonInfo('path')
        subprocess.Popen(path + '/grilohttpd')
        page = get_page_retry(GRILOHTTPD)
        content = parse_page(page)
        build_link_list(content)
    elif mode[0] == 'dir':
        page = get_page(GRILOHTTPD + urllib.quote_plus(args['url'][0]))
        content = parse_page(page)
        build_link_list(content)
    elif mode[0] == 'stream':
        play_song(args['url'][0])
    
if __name__ == '__main__':
    addon_handle = int(sys.argv[1])
    main()
