import os
import logging
import time
import re
import urllib
import urllib2
import json
from datetime import datetime
from datetime import timedelta
import mysql.connector
import mysql as mariadb
import random
import system_defines

logging.basicConfig(filename="/var/www/epg/log.txt", level=logging.DEBUG)

apiKey = 'ke5cc5vnjczre7pr6rsw8psz'

class Lineup:
    def __init__(self):
        self.id = ""
        self.name = ""


class Channel:
    def __init__(self):
        self.id = ""
        self.callSign = ""
        self.affiliateCallSign = ""
        self.name = ""
        self.number = ""   # has to handle various dot notations just in cast
        self.imageUrl = ""


class Program:
    def __init__(self):
        self.title = ""
        self.startTime = None
        self.durationMins = 0
        self.description = "NA"
        self.imageUrl = "NA"
        self.genres = "NA"
        self.cast = "NA"


def test():
    mariadb_connection = mariadb.connector.connect(user='root', password=system_defines.mariaDbPassword)
    cursor = mariadb_connection.cursor(buffered=True)
    cursor.execute("use zvepg")

    try:
        cursor.execute("drop table lineups")
    except mariadb.connector.Error:
        pass

    try:
        cursor.execute("drop table lineupChannels")
    except mariadb.connector.Error:
        pass

    mariadb_connection.commit()
    cursor.close()

def getLineup():
    mso = "DIRECTV"
    zip = "01720"
    url = 'https://data.tmsapi.com/v1.1/lineups'
    values = {'api_key': apiKey,
              'country': 'USA', 'postalCode': zip}

    # headers = {'User-Agent': 'Mozilla 5.10'}

    lineupFound = Lineup()

    data = urllib.urlencode(values)
    fullurl = url + '?' + data
    req = urllib2.Request(fullurl)
    logging.debug(u"EPG_GRACE.PY: getLineup URL={}".format(fullurl))

    try:
        rawResponse = urllib2.urlopen(req)
    except urllib2.URLError as e:
        logging.debug(u"EPG_GRACE.PY: getLineup FAILED URL={}, error={}".format(fullurl, e))
        return lineupFound

    responseJson = rawResponse.read()

    lineups = json.loads(responseJson)

    for lineup in lineups:
        print lineup
        if 'mso' in lineup:
            if lineup["mso"]["name"] == mso:
                lineupFound.id = lineup["lineupId"]
                lineupFound.name = lineup["name"]
                break
    return lineupFound
