#!/usr/bin/python2
# import MySQL module

import MySQLdb
import sys
import getopt
import socket
import os
import time
import string

def LIVETV():
    grandtotal=0
    global rectv_total
    global rectv_time
    global livetv_total
    global livetv_time
    # create a cursor
    cursor = db.cursor()
    # execute SQL statement

    cursor.execute("SELECT unix_timestamp(starttime),unix_timestamp(endtime),title FROM recorded where recgroup=(%s) ORDER by starttime;" , ("livetv"))
    result = cursor.fetchall()

    for row in result:
      #  print row[0], row[1] ,row [2]
        start=row[0]
        end=row[1]
        if ( end  > start ):
            total = (end - start) /60
            grandtotal+=total
    hours = grandtotal / 60.0
    days = hours / 24.0

    livetv_total=len(result)
    livetv_time=hours



def RECORDTV():
    grandtotal=0
    global rectv_total
    global rectv_time
    global livetv_total
    global livetv_time
    # create a cursor
    cursor = db.cursor()
    # execute SQL statement

    cursor.execute("SELECT unix_timestamp(starttime),unix_timestamp(endtime),title FROM recorded where not recgroup=(%s) ORDER by starttime;" , ("livetv"))
    result = cursor.fetchall()

    for row in result:
      #  print row[0], row[1] ,row [2]
        start=row[0]
        end=row[1]
        if ( end  > start ):
            total = (end - start) /60
            grandtotal+=total
    hours = grandtotal / 60.0
    days = hours / 24.0

    rectv_total=len(result)
    rectv_time=hours



def printvars():
    print rectv_time
    print rectv_total
    print livetv_time
    print livetv_total

def sendTObb():
    DATE = time.strftime("%a %b %d %H:%M:%S %Z %Y", time.localtime(time.time()))
    if os.environ['BB']:
        #print os.environ['BB']
        BB=os.environ['BB']
    if os.environ['BBDISP']:
        #print os.environ['BBDISP']
        BBDISP=os.environ['BBDISP']
    if os.environ['MACHINE']:
       # print os.environ['MACHINE']
        MACHINE=os.environ['MACHINE']

  #  MACHINE = socket.gethostname()
  #  MACHINE = string.replace(MACHINE, '.', ',')
    INFOLINE= "\n rectv_total:" + str(rectv_total)
    INFOLINE= INFOLINE + "\n rectv_time:" + str(rectv_time)
    INFOLINE= INFOLINE + "\n livetv_total:" + str(livetv_total)
    INFOLINE= INFOLINE + "\n livetv_time:" + str(livetv_time)
    INFOLINE= INFOLINE + "\n "



    LINE = "status " + MACHINE + ".storage green" + " " + DATE + " " + INFOLINE

    cmd = BB + ' ' + BBDISP + ' "' + LINE + '"'
    os.system(cmd)
    #print LINE

def main(argv):
    global db
    global rectv_total
    global rectv_time
    global livetv_total
    global livetv_time

    rectv_total=0
    rectv_time=0
    livetv_total=0
    livetv_time=0

    db = MySQLdb.connect(host="localhost", user="mythtv", passwd="mythtv", db="mythconverg")

    LIVETV()
    RECORDTV()
    #printvars()
    sendTObb()
if __name__ == "__main__":
    main(sys.argv[1:])