class APICache:
  def __init__(self, plugin=None):
    self.api = NetworkTenVideo()
    self.log = plugin.log
    self.log.debug('Cache TTL set to %d minutes', config.CACHE_TTL)
    self.cache = plugin.get_storage('showlist', TTL=config.CACHE_TTL)
    print repr(self.cache)

  def get_show(self, show, bypassCache=False):
    if not bypassCache and 'showlist' in self.cache and show in self.cache['showlist']:
      self.log.debug('Retrieving show data for show "%s" from cache...', show)
      show_data = self.cache['showlist'][show]
    else:
      self.log.debug('Retrieving show data for show "%s" from api ...', show)
      show_data = self.api.get_show(show)
      if not 'showlist' in self.cache:
        self.cache['showlist'] = {}
      self.cache['showlist'][show_data.showName] = show_data
      self.cache.sync()

    self.log.debug('Show data: %s', repr(show_data))

    return show_data

  def get_shows(self, bypassCache=False):
    if not bypassCache and 'showlist' in self.cache:
      self.log.debug('Retrieving show list from cache...')
      shows = self.cache['showlist'].values()
    else:
      self.log.debug('Retrieving show list from api...')
      shows = self.api.get_shows().items
      if not 'showlist' in self.cache:
        self.cache['showlist'] = {}
      for show in shows:
        self.cache['showlist'][show.showName] = show
      self.cache.sync()

    self.log.debug('Shows: %s', repr(shows))

    return shows

  def get_playlists(self, show, bypassCache=False):
    if not bypassCache and 'showlist' in self.cache and show in self.cache['showlist'] and self.cache['showlist'][show].playlists and len(self.cache['showlist'][show].playlists) > 0:
      self.log.debug('Retrieving playlists for show "%s" from cache...', show)
      playlists = self.cache['showlist'][show].playlists
    else:
      self.log.debug('Retrieving playlists for show "%s" from api...', show)
      playlists = self.api.get_playlists_for_show(show).items
      if show in cache['showlist']:
        self.cache['showlist'][show].playlists = playlists
        self.cache.sync()

    self.log.debug('Playlists: %s', repr(playlists.items))

    return playlists

  def search_videos(self, bypassCache=False, **kwargs):
    key = json.dumps(kwargs)
    print repr(key)
    if not bypassCache and 'searches' in self.cache and key in self.cache['searches']:
      self.log.debug('Using search results from cache...')
      result = self.cache['searches'][key]
    else:
      self.log.debug('Using search results from api...')
      result = self.api.search_videos(**kwargs)
      if not 'searches' in self.cache:
        self.cache['searches'] = {}
      self.cache['searches'][key] = result
      self.cache.sync()
    return result
    def showlist(self, type):
        api = NetworkTenVideo(self.plugin.cached(TTL=config.CACHE_TTL))
        shows = []
        if "news" == type:
            for news in api.get_news():
                fanart_url = api.get_fanart(news)

                item = ListItem.from_dict(
                    label=news["Title"],
                    path=self.url_for(
                        "videolist.videolist",
                        explicit=True,
                        query=news["BCQueryForVideoListing"],
                        page="0",
                        fanart=fanart_url,
                    ),
                )

                if fanart_url:
                    item.set_property("fanart_image", fanart_url)

                if "Thumbnail" in news:
                    url = news["Thumbnail"]
                    if url.startswith("//"):
                        url = "http:" + url
                    item.set_thumbnail(url)
                shows.append(item)
        elif "sport" == type:
            for sport in api.get_sports():
                item = ListItem.from_dict(
                    label=sport["Title"],
                    path=self.url_for(
                        "videolist.videolist", explicit=True, query=sport["BCQueryForVideoListing"], page="0"
                    ),
                )
                shows.append(item)
        elif "live" == type:
            for category in api.get_live_categories():
                fanart_url = None

                if "fanart" in category:
                    fanart_url = category["fanart"]

                item = ListItem.from_dict(
                    label=category["title"],
                    path=self.url_for(
                        "videolist.videolist", explicit=True, query=category["query"], page="0", fanart=fanart_url
                    ),
                )

                if fanart_url:
                    item.set_property("fanart_image", fanart_url)

                if "thumbnail" in category:
                    item.set_thumbnail(category["thumbnail"])

                shows.append(item)
        else:  # tvshows
            for show in api.get_shows():
                info_dict = {}
                if show["IsLongFormAvailable"] is not True:  # todo: make this a setting
                    continue
                if "Genres" in show and len(show["Genres"]):
                    info_dict["genre"] = show["Genres"][0]["Name"]
                if "Description" in show:
                    info_dict["plot"] = show["Description"]
                if "CurrentSeasonFirstEpisodeAirDateTime" in show:
                    try:
                        date = time.strptime(show["CurrentSeasonFirstEpisodeAirDateTime"], "%d-%m-%Y %H:%M:%S %p")
                        info_dict["aired"] = time.strftime("%Y-%m-%d", date)
                        info_dict["premiered"] = time.strftime("%Y-%m-%d", date)
                        info_dict["year"] = time.strftime("%Y", date)
                    except Exception, e:
                        pass
                if "Channel" in show:
                    info_dict["studio"] = show["Channel"]
                if "NumberOfVideosFromBCQuery" in show:
                    # not technically correct as this also returns the number of short form as well but close enough
                    info_dict["episode"] = show["NumberOfVideosFromBCQuery"]

                if "BCQueryForVideoListing" in show and len(show["BCQueryForVideoListing"]):
                    query = urlparse.parse_qs(show["BCQueryForVideoListing"], True)
                    if "all" not in query:
                        query["all"] = []
                    elif not isinstance(query["all"], list):
                        query["all"] = [query["all"]]

                    query["all"].append("video_type_long_form:Full Episode")

                    # some shows (Australian Survivor) have typos in the query, which break with exact matching
                    if "video_type_long_form:Full Episodes" in query["all"]:
                        query["all"].remove("video_type_long_form:Full Episodes")
                else:
                    continue

                fanart_url = api.get_fanart(show)

                item = ListItem.from_dict(
                    label=show["Title"],
                    path=self.url_for(
                        "videolist.videolist", explicit=True, query=urllib.urlencode(query, True), fanart=fanart_url
                    ),  # ShowPageItemId=show['ShowPageItemId']
                    info=info_dict,
                )

                if fanart_url:
                    item.set_property("fanart_image", fanart_url)

                if "Thumbnail" in show:
                    url = show["Thumbnail"]
                    if url.startswith("//"):
                        url = "http:" + url
                    item.set_thumbnail(url)
                shows.append(item)
  def showlist(self, type):
    api = NetworkTenVideo(self.plugin.cached(TTL=config.CACHE_TTL))
    shows = []
    if 'news' == type:
      for news in api.get_news():
        fanart_url = api.get_fanart(news)

        item = ListItem.from_dict(
          label=news['Title'],
          path=self.url_for('videolist.videolist', explicit=True, query=news['BCQueryForVideoListing'], page='0', fanart=fanart_url),
        )

        if fanart_url:
          item.set_property('fanart_image', fanart_url)

        if 'Thumbnail' in news:
          url = news['Thumbnail']
          if url.startswith('//'):
            url = 'http:' + url
          item.set_thumbnail(url)
        shows.append(item)
    elif 'sport' == type:
      for sport in api.get_sports():
        item = ListItem.from_dict(
          label=sport['Title'],
          path=self.url_for('videolist.videolist', explicit=True, query=sport['BCQueryForVideoListing'], page='0'),
        )
        shows.append(item)
    elif 'live' == type:
      for category in api.get_live_categories():
        fanart_url = None

        if 'fanart' in category:
          fanart_url = category['fanart']

        item = ListItem.from_dict(
          label=category['title'],
          path=self.url_for('videolist.videolist', explicit=True, query=category['query'], page='0', fanart=fanart_url),
        )

        if fanart_url:
          item.set_property('fanart_image', fanart_url)

        if 'thumbnail' in category:
          item.set_thumbnail(category['thumbnail'])

        shows.append(item)
    else: #tvshows
      for show in api.get_shows():
        info_dict = {}
        if show['IsLongFormAvailable'] is not True: #todo: make this a setting
          continue
        if 'Genres' in show and len(show['Genres']):
          info_dict['genre'] = show['Genres'][0]['Name']
        if 'Description' in show:
          info_dict['plot'] = show['Description']
        if 'CurrentSeasonFirstEpisodeAirDateTime' in show:
          try:
            date = time.strptime(show['CurrentSeasonFirstEpisodeAirDateTime'],'%d-%m-%Y %H:%M:%S %p')
            info_dict['aired'] = time.strftime('%Y-%m-%d', date)
            info_dict['premiered'] = time.strftime('%Y-%m-%d', date)
            info_dict['year'] = time.strftime('%Y', date)
          except Exception, e:
            pass
        if 'Channel' in show:
          info_dict['studio'] = show['Channel']
        if 'NumberOfVideosFromBCQuery' in show:
          # not technically correct as this also returns the number of short form as well but close enough
          info_dict['episode'] = show['NumberOfVideosFromBCQuery']

        if 'BCQueryForVideoListing' in show and len(show['BCQueryForVideoListing']):
          query = urlparse.parse_qs(show['BCQueryForVideoListing'], True)
          if 'all' not in query:
            query['all'] = []
          elif not isinstance(query['all'], list):
            query['all'] = [ query['all'] ]
          query['all'].append('video_type_long_form:Full Episode')
        else:
          continue

        fanart_url = api.get_fanart(show)

        item = ListItem.from_dict(
          label=show['Title'],
          path=self.url_for('videolist.videolist', explicit=True, query=urllib.urlencode(query, True), fanart=fanart_url), #ShowPageItemId=show['ShowPageItemId']
          info=info_dict
        )

        if fanart_url:
          item.set_property('fanart_image', fanart_url)

        if 'Thumbnail' in show:
          url = show['Thumbnail']
          if url.startswith('//'):
            url = 'http:' + url
          item.set_thumbnail(url)
        shows.append(item)