
import weechat
import sys
import json
#import urllib.request
import urllib
import urlopen
#from urllib.request import urlopen


ICESTATS = {
    'SCRIPT_NAME'     : 'icestats',
    'SCRIPT_COMMAND'  : 'icestats',
    'default_options' : {
        },
}

def mpv_msg(world,world_eol,userdata):
    url = 'http://icecast.nashgul.com.es/status-json.xsl'
    response = urlopen(url)
    string = response.read().decode('utf-8')
    json_obj = json.loads(string)
    my_obj = json_obj["icestats"]["source"]
    stations = len(my_obj)
    if my_obj == []:
        print ('No Data!')
    else:
        for (x) in range(stations):
            try:
                np = my_obj[x]["server_name"] + ": " + my_obj[x]["artist"] + " " + my_obj[x]["title"] + " " + my_obj[x]["listenurl"]
                message = '%s' % ICESTATS['message'] + np
                weechat.command(weechat.current_buffer(), message)
                return weechat.WEECHAT_RC_OK
            except:
                e = sys.exc_info()[0]
                if my_obj[x]["server_name"] == "Birras icecast: freenode.#birras":
                    pass
                else:
                    weechat.prnt('', '%s: some stations are missing matadata' % ICESTATS['SCRIPT_NAME'])
                    return weechat.WEECHAT_RC_ERROR
weechat.register(ICESTATS['SCRIPT_NAME'], "llua", "0.1", "The Beer-ware License", "Now Playing for icecast2", "", "")
