import os
import socket
import logging
import urllib
import urllib2
import json
import epg_db
from datetime import datetime
from datetime import timedelta

# DOCUMENTATION: http://developer.tmsapi.com/
# TEST service: curl http://data.tmsapi.com/v1.1/stations/10021?api_key=ke5cc5vnjczre7pr6rsw8psz

apiKey = 'ke5cc5vnjczre7pr6rsw8psz'

# curl "http://data.tmsapi.com/v1.1/lineups?country=USA&postalCode=78701&api_key=ke5cc5vnjczre7pr6rsw8psz"


def getProviders(country, postalCode):
    url = 'http://data.tmsapi.com/v1.1/lineups'
    values = {'api_key': apiKey,
              'country': country, 'postalCode': postalCode}

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

    providers = []
    data = urllib.urlencode(values)
    fullurl = url + '?' + data
    req = urllib2.Request(fullurl)
    try:
        rawResponse = urllib2.urlopen(req)
    except urllib2.URLError:
        return providers

    responseJson = rawResponse.read()
    gnLineups = json.loads(responseJson)

    for gnLineup in gnLineups:
        provider = epg_db.Provider()
        provider.id = gnLineup["lineupId"]
        provider.name = gnLineup["name"]
        providers.append(provider)

    return providers


def getProviderChannels(providerId):
    url = "http://data.tmsapi.com/v1.1/lineups/{}/channels".format(providerId)
    values = {'api_key': apiKey}
    # headers = {'User-Agent': 'Mozilla 5.10'}

    data = urllib.urlencode(values)
    fullurl = url + '?' + data
    req = urllib2.Request(fullurl)
    try:
        rawResponse = urllib2.urlopen(req)
    except urllib2.URLError:
        return []

    responseJson = rawResponse.read()

    providerChannels = json.loads(responseJson)

    channels = []
    name = ""            # have to make a seperate web access for EACH channel to get this and
    imageUrl = ""        # this (one request for both)... takes forever, so doing in background
    for providerChannel in providerChannels:
        if "stationId" in providerChannel and "callSign" in providerChannel and "channel" in providerChannel:
            #        name = getProviderChannelName(providerId, providerChannel["stationId"])

            channel = epg_db.Channel()
            channel.id = providerChannel["stationId"]
            channel.callSign = providerChannel["callSign"]
            channel.name = name
            channel.number = str(int(providerChannel["channel"]))
            channel.imageUrl = imageUrl
        else:
            pass

        if "affiliateCallSign" in providerChannel:
            channel.affiliateCallSign = providerChannel["affiliateCallSign"]

        channels.append(channel)

    return channels


def getChannelInfo(channelId):
    url = "http://data.tmsapi.com/v1.1/stations/{}".format(channelId)
    values = {'api_key': apiKey}
    # headers = {'User-Agent': 'Mozilla 5.10'}

    channel = epg_db.Channel()

    data = urllib.urlencode(values)
    fullurl = url + '?' + data
    req = urllib2.Request(fullurl)
    logging.debug("EPG_GRACE.PY: getChannelInfo getting channel info")
    try:
        rawResponse = urllib2.urlopen(req)
    except urllib2.URLError as e:
        logging.debug(u"EPG_GRACE.PY: getChannelInfo Web ERROR {}".format(e))
        return channel

    responseJson = rawResponse.read()
    response = json.loads(responseJson)

    channel.name = "unavailable"
    if "name" in response[0]:
        channel.name = response[0]["name"]

    channel.imageUrl = "unavailable"
    if "preferredImage" in response[0]:
        imageUrl = response[0]["preferredImage"]["uri"]
        if imageUrl != "":
            channel.imageUrl = "art/channelIcons/" + imageUrl
            # check to see if icon is local and if not, get it
            if not os.path.exists(channel.imageUrl):
                path = os.path.dirname(channel.imageUrl)
                if not os.path.exists(path):
                    os.makedirs(path)
                logging.debug("EPG_GRACE.PY: getChannelInfo getting Channel icon")
                url = getFullImageUrl(imageUrl)
                try:
                    urllib.urlretrieve(url, channel.imageUrl)
                except:
                    logging.debug("EPG_GRACE.PY: getChannelInfo Channel icon download failed")
                    channel.imageUrl = "unavailable"
                    return channel

    logging.debug("EPG_GRACE.PY: getChannelInfo return")
    return channel


def getFullImageUrl(url):
    return "http://developer.tmsimg.com/" + url + "?api_key=" + apiKey


def getPrograms(channelId):
    # From earliest time zone now (utc - 12), to 48 hours from then + 3
    beforeHours = timedelta(hours=12)
    afterHours = timedelta(hours=39)
    startDate = datetime.utcnow() - beforeHours
    endDate = datetime.utcnow() + afterHours

    url = "http://data.tmsapi.com/v1.1/stations/{}/airings".format(channelId)
    values = {'api_key': apiKey,
              'startDateTime': startDate.strftime("%Y-%m-%dT%H:%MZ"),
              'endDateTime': endDate.strftime("%Y-%m-%dT%H:%MZ")}

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

    data = urllib.urlencode(values)
    fullurl = url + '?' + data
    logging.debug(u"EPG_GRACE.PY: getProgram grace fetch url: {}".format(fullurl))
    req = urllib2.Request(fullurl)
    try:
        rawResponse = urllib2.urlopen(req, timeout=10)
    except urllib2.URLError as e:
        logging.debug(u"EPG_GRACE.PY: getPrograms: grace fetch error={}".format(e))
        return []
    except socket.timeout as e:
        logging.debug(u"EPG_GRACE.PY: getPrograms: grace timeout={}".format(e))
        return []

    responseJson = rawResponse.read()

    logging.debug("EPG_GRACE.PY: getProgram grace fetch done")

    response = []
    try:
        response = json.loads(responseJson)
    except json.JSONDecodeError:
        logging.debug("EPG_GRACE.PY: getProgram Json decode error")
        return []

    programs = []
    for i in range(0, len(response)):
        program = epg_db.Program()
        program.title = response[i]["program"]["title"]
        program.startTime = response[i]["startTime"]
        program.durationMins = response[i]["duration"]
        program.description = response[i]["program"]["longDescription"] if "longDescription" in response[i]["program"] else ""

        program.imageUrl = "unavailable"
        imageUrl = response[i]["program"]["preferredImage"]["uri"] if "preferredImage" in response[i]["program"] else ""
        # Check if local copy exists.... and if not, get it
        if imageUrl != "":
            program.imageUrl = "art/programIcons/" + imageUrl
            if not os.path.exists(program.imageUrl):
                path = os.path.dirname(program.imageUrl)
                if not os.path.exists(path):
                    os.makedirs(path)
                url = getFullImageUrl(imageUrl)
                try:
                    urllib.urlretrieve(url, program.imageUrl)
                except:
                    logging.debug("EPG_GRACE.PY: getProgram: icon downloaded error")
                    program.imageUrl = "unavailable"

        program.genres = ",".join(response[i]["program"]["genres"]) if "genres" in response[i]["program"] else ""
        program.cast = ",".join(response[i]["program"]["topCast"]) if "topCast" in response[i]["program"] else ""
        programs.append(program)

    logging.debug("EPG_GRACE.PY: getProgram grace fetch images done")

    return programs
