#!/usr/bin/python2

import urllib2
import xml.etree.ElementTree as ET
import socket
from  MythTV import Frontend
import sys
#socket.setdefaulttimeout(1)
#socket.setdefaulttimeout(.00001)

def msg(msg):
    #if cmdargs.silent is False:
    print "%s" %msg


def parse_xml(frontend):
    temp_dict = {'state':" --- ",
                 'title':" --- ",
                 'subtitle':" --- ",
                 'location':" --- "}
    url = "http://%s:6547/Frontend/GetStatus" %frontend
    try:
        request = urllib2.Request(url)
        xml = urllib2.urlopen(request,timeout=1)
        tree = ET.parse(xml)
        root = tree.getroot()
    except:
        msg("   Couldn't connect to %s" %frontend)
        return temp_dict

    lst = root.find("State")
    for item in lst:
            try:
                keyitem = (item.find('Key').text).strip()
                valueitem  = (item.find('Value').text).strip()
            except:
                continue
            if keyitem == "state":
                temp_dict['state'] = valueitem

            elif keyitem == "title":
                temp_dict['title'] = valueitem

            elif keyitem == "subtitle":
                temp_dict['subtitle'] = valueitem

            elif keyitem == "currentlocation":
                temp_dict['location'] = valueitem

    return temp_dict


def mythfe_status(cursor,mythDB):
    frontends=list(Frontend.fromUPNP())
    status_dict={}
    #try:
        #frontends = mythDB.getFrontends() #use cursor instead so it doesn't test connection
        #cursor.execute("select hostname from settings where value = 'FrontendIdleTimeout'")
        #frontends=cursor.fetchall()
    #except:
        #msg("Excptions")
        #return

    for i in frontends:
        try:
            fe_hostname = socket.gethostbyaddr(i.host)[0]
        except:
            print "DNS lookup failed for %s" %i.host
            fe_hostname = i.host
        status_dict[fe_hostname] = parse_xml(i.host)

    return status_dict


def print_html(status_dict):
    print '<div> <p></p>'
    print '</br> </br> '
    print '<table class="calllog">'

    #print "Current state of all online frontends"
    #print '</br> </br> '

    #print status_dict
    row = '''
<tr>
    <td> %s  </td>
    <td> %s  </td>
    <td> %s  </td>
    <td> %s  </td>
    <td> %s  </td>
</tr>
'''
    print row %("  MythFrontend Host  ","  State  ","  Title  ","  Subtitle  ","  MythFrontend Location  ")
    for fe in status_dict.keys():
        temp_dict = status_dict[fe]
        print row %(fe,
                    temp_dict['state'],
                    temp_dict['title'],
                    temp_dict['subtitle'],
                    temp_dict['location'])

    print "</table>"
    print '</div>'

    print '''
    <div id="footer">
       </br>
       <p>Offline systems are not listed</p>
    </div>
'''


def main():
    try:
        from MythTV import MythDB
        mythDB = MythDB()
        cursor = mythDB.cursor()
        db_conn=True
    except:
        msg("Couldn't connect to MythTV database.")
        db_conn=False

    try:
        from MythTV import MythBE
        mythBE = MythBE()
        be_conn=True
    except:
        msg("Couldn't connect to MythTV backend.")
        be_conn=False

    if (db_conn):
        status_dict = mythfe_status(cursor,mythDB)
        print_html(status_dict)



if __name__ == "__main__":
    main()
