import urllib2
import json
import time

from core.helpers.decorator import Cached
from core.helpers.config import config
from core.helpers.logger import log, LogLevel


@Cached
def __request(request):
    log('Send Fanart Request: ' + request.replace(config.fanart.api_key, 'XXX'), 'DEBUG')
    headers = {'Accept': 'application/json'}

    _request = urllib2.Request(request, headers=headers)
    response_body = urllib2.urlopen(_request).read()
    result = json.loads(response_body)

    return result


def _get(video_type, movie_id, output_format='JSON'):
    req = '{0}{1}/{2}/{3}/{4}'.format(config.fanart.url_base, video_type,
                                      config.fanart.api_key, movie_id, output_format)
    try_again = True
    n = 0
    while try_again and n < 10:
        try:
            return __request(req)
        except urllib2.HTTPError:
            n += 1
            try_again = True
            log('Ooops.. FanartTV Error - Try again', LogLevel.Warning)
            time.sleep(2)


def get_movie(tmdb_id):
    return _get(video_type='movie', movie_id=tmdb_id)


def get_show(tvdb_id):
    return _get(video_type='series', movie_id=tvdb_id)
[((15, 15, 15, 56), 'urllib2.Request', 'urllib2.Request', (), '', False, 'import urllib2\n'), ((17, 13, 17, 38), 'json.loads', 'json.loads', ({(17, 24, 17, 37): 'response_body'}, {}), '(response_body)', False, 'import json\n'), ((16, 20, 16, 45), 'urllib2.urlopen', 'urllib2.urlopen', ({(16, 36, 16, 44): '_request'}, {}), '(_request)', False, 'import urllib2\n'), ((33, 12, 33, 71), 'core.helpers.logger.log', 'log', ({(33, 16, 33, 52): '"""Ooops.. FanartTV Error - Try again"""', (33, 54, 33, 70): 'LogLevel.Warning'}, {}), "('Ooops.. FanartTV Error - Try again', LogLevel.Warning)", False, 'from core.helpers.logger import log, LogLevel\n'), ((34, 12, 34, 25), 'time.sleep', 'time.sleep', ({(34, 23, 34, 24): '(2)'}, {}), '(2)', False, 'import time\n')]