# Path: spacescout_web/views/home.py
# def fetch_open_now_for_campus(
#                             request, campus, use_cache=True,
#                             fill_cache=False, cache_period=FIVE_MINUTE_CACHE):
#     if campus is None:
#         # Default to zooming in on the UW Seattle campus
#         center_latitude = '47.655003'
#         center_longitude = '-122.306864'
#         zoom_level = '15'
#         distance = '500'
# 
#     else:
#         location = settings.SS_LOCATIONS[campus]
#         center_latitude = location['CENTER_LATITUDE']
#         center_longitude = location['CENTER_LONGITUDE']
#         zoom_level = location['ZOOM_LEVEL']
# 
#         if 'DISTANCE' in location:
#             distance = location['DISTANCE']
#         else:
#             distance = '500'
# 
#     # SPOT-1832. Making the distance far enough that center of campus to
#     # furthest spot from the center can be found
#     distance = 1000
#     consumer = oauth2.Consumer(
#                             key=settings.SS_WEB_OAUTH_KEY,
#                             secret=settings.SS_WEB_OAUTH_SECRET)
#     client = oauth2.Client(consumer)
# 
#     chain = SearchFilterChain(request)
#     search_url_args = []
#     search_url_args = chain.url_args(request)
#     search_url_args.append({'center_latitude': center_latitude})
#     search_url_args.append({'center_longitude': center_longitude})
#     search_url_args.append({'open_now': '1'})
#     search_url_args.append({'distance': distance})
#     search_url_args.append({'limit': '0'})
# 
#     return get_space_json(
#                         client, search_url_args, use_cache,
#                         fill_cache, cache_period)
# 
# Path: spacescout_web/views/image.py
# def get_multi_image(
#                     spot_id, image_ids, constrain, thumb_width=None,
#                     thumb_height=None, fill_cache=False):
#     if constrain is True:
#         constraint = []
#         if thumb_width:
#             constraint.append("width:%s" % thumb_width)
#         if thumb_height:
#             constraint.append("height:%s" % thumb_height)
#         url = "{0}/api/v1/multi_image/{2}/thumb/constrain/{3}".format(
#                                                 settings.SS_WEB_SERVER_HOST,
#                                                 spot_id, image_ids,
#                                                 ','.join(constraint))
#     else:
#         url = "{0}/api/v1/multi_image/{2}/thumb/{3}x{4}".format(
#                                                 settings.SS_WEB_SERVER_HOST,
#                                                 spot_id, image_ids,
#                                                 thumb_width, thumb_height)
# 
#     image_cache_key = "spot_multi_image_%s" % hashlib.sha224(url).hexdigest()
#     offsets_cache_key = "spot_multi_image_offsets_%s" % (
#                                             hashlib.sha224(url).hexdigest())
# 
#     if fill_cache:
#         client = get_client()
#         resp, content = client.request(url, 'GET')
#         cache.set(image_cache_key, content)
#         cache.set(offsets_cache_key, resp['sprite-offsets'])
# 
#     cached_image = cache.get(image_cache_key)
#     cached_offsets = cache.get(offsets_cache_key)
# 
#     if not cached_offsets or not cached_image:
#         return None, None
# 
#     return {
#         'Content-Type': 'image/jpeg',
#         'Sprite-Offsets': cached_offsets
#     }, cached_image


from django.core.management.base import BaseCommand
from django.conf import settings
from spacescout_web.views.home import fetch_open_now_for_campus
from spacescout_web.views.image import get_multi_image



class Command(BaseCommand):
    help = ("Fills a cache with the json and image data for open spaces "
            "in all campuses")

    def handle(self, *args, **kwargs):
        if not hasattr(settings, 'SS_LOCATIONS'):
            raise("Error running load_open_now_cache - you need "
                  "to define your locations")

        for location in settings.SS_LOCATIONS:
            image_ids = []
            spaces = fetch_open_now_for_campus(location,
                                               use_cache=False,
                                               fill_cache=True)

            for space in spaces:
                if len(space["images"]) > 0:
                    image_ids.append("%i" % space["images"][0]["id"])

            if len(image_ids):

# Path: spacescout_web/views/home.py
# def fetch_open_now_for_campus(
#                             request, campus, use_cache=True,
#                             fill_cache=False, cache_period=FIVE_MINUTE_CACHE):
#     if campus is None:
#         # Default to zooming in on the UW Seattle campus
#         center_latitude = '47.655003'
#         center_longitude = '-122.306864'
#         zoom_level = '15'
#         distance = '500'
# 
#     else:
#         location = settings.SS_LOCATIONS[campus]
#         center_latitude = location['CENTER_LATITUDE']
#         center_longitude = location['CENTER_LONGITUDE']
#         zoom_level = location['ZOOM_LEVEL']
# 
#         if 'DISTANCE' in location:
#             distance = location['DISTANCE']
#         else:
#             distance = '500'
# 
#     # SPOT-1832. Making the distance far enough that center of campus to
#     # furthest spot from the center can be found
#     distance = 1000
#     consumer = oauth2.Consumer(
#                             key=settings.SS_WEB_OAUTH_KEY,
#                             secret=settings.SS_WEB_OAUTH_SECRET)
#     client = oauth2.Client(consumer)
# 
#     chain = SearchFilterChain(request)
#     search_url_args = []
#     search_url_args = chain.url_args(request)
#     search_url_args.append({'center_latitude': center_latitude})
#     search_url_args.append({'center_longitude': center_longitude})
#     search_url_args.append({'open_now': '1'})
#     search_url_args.append({'distance': distance})
#     search_url_args.append({'limit': '0'})
# 
#     return get_space_json(
#                         client, search_url_args, use_cache,
#                         fill_cache, cache_period)
# 
# Path: spacescout_web/views/image.py
# def get_multi_image(
#                     spot_id, image_ids, constrain, thumb_width=None,
#                     thumb_height=None, fill_cache=False):
#     if constrain is True:
#         constraint = []
#         if thumb_width:
#             constraint.append("width:%s" % thumb_width)
#         if thumb_height:
#             constraint.append("height:%s" % thumb_height)
#         url = "{0}/api/v1/multi_image/{2}/thumb/constrain/{3}".format(
#                                                 settings.SS_WEB_SERVER_HOST,
#                                                 spot_id, image_ids,
#                                                 ','.join(constraint))
#     else:
#         url = "{0}/api/v1/multi_image/{2}/thumb/{3}x{4}".format(
#                                                 settings.SS_WEB_SERVER_HOST,
#                                                 spot_id, image_ids,
#                                                 thumb_width, thumb_height)
# 
#     image_cache_key = "spot_multi_image_%s" % hashlib.sha224(url).hexdigest()
#     offsets_cache_key = "spot_multi_image_offsets_%s" % (
#                                             hashlib.sha224(url).hexdigest())
# 
#     if fill_cache:
#         client = get_client()
#         resp, content = client.request(url, 'GET')
#         cache.set(image_cache_key, content)
#         cache.set(offsets_cache_key, resp['sprite-offsets'])
# 
#     cached_image = cache.get(image_cache_key)
#     cached_offsets = cache.get(offsets_cache_key)
# 
#     if not cached_offsets or not cached_image:
#         return None, None
# 
#     return {
#         'Content-Type': 'image/jpeg',
#         'Sprite-Offsets': cached_offsets
#     }, cached_image


# Path: spacescout_web/management/commands/load_open_now_cache.py
from django.core.management.base import BaseCommand
from django.conf import settings
from spacescout_web.views.home import fetch_open_now_for_campus
from spacescout_web.views.image import get_multi_image




class Command(BaseCommand):
    help = ("Fills a cache with the json and image data for open spaces "
            "in all campuses")

    def handle(self, *args, **kwargs):
        if not hasattr(settings, 'SS_LOCATIONS'):
            raise("Error running load_open_now_cache - you need "
                  "to define your locations")

        for location in settings.SS_LOCATIONS:
            image_ids = []
            spaces = fetch_open_now_for_campus(location,
                                               use_cache=False,
                                               fill_cache=True)

            for space in spaces:
                if len(space["images"]) > 0:
                    image_ids.append("%i" % space["images"][0]["id"])

            if len(image_ids):

                get_multi_image(None,