import os
import logging
import cached_url, thumbnail
from urllib2 import urlopen
from StringIO import StringIO

#logging.basicConfig(level=logging.DEBUG,
#                    format='%(asctime)s %(levelname)s %(message)s',
#                    filename='cached.log',
#                    filemode='w')

console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

def get_content(url, width=None, height=None, scale=None, control=False):
    """get cached content"""
    key = '%s::%s::%s::%s' % (url, str(height), str(width), str(scale))
    content = cached_url.mc.get(key)
    if content is not None:
        logging.debug('%s cached' % key)
        return content
    infos, content = cached_url.get_content(url, control)
    try:
        content = thumbnail.generate(StringIO(content), width, height, scale)
    except IOError:
        content = None
    cached_url.mc.set(key, (infos, content))
    logging.debug('%s caching' % key)
    return infos, content

