# -*- coding: utf-8 -*-

from os import environ
from datetime import date
from datetime import datetime
from requests import get
from calendar import Calendar

import records

DNZ_URL = 'http://api.digitalnz.org/v3/records/'
DNZ_KEY = environ.get('DNZ_KEY')


def get_metadata(record):
    """
    Calls DNZ's API to retrieve the metadata for a given record.
    """

    id = record['id']

    url = DNZ_URL + '{id}.json?api_key={key}'.format(id=id, key=DNZ_KEY)

    metadata = get(url).json()['record']
    metadata['hash'] = record['hash']

    return metadata


def get_calendar():
    """
    Generates a calendar structure for the current month.
    """

    year = date.today().year
    month = date.today().month

    return Calendar(0).monthdatescalendar(year, month)


def update_record_cache(cache={}):
    """
    Fills the cache with values for the record of the day if necessary.
    """

    today = date.today()

    if ('day' not in cache) or (today != cache['day']):
        print('Invalidating cache for ' + str(today))

        cache['day'] = today

        try:
            cache['record'] = records.get_record_by_date(str(cache['day']))
            cache['metadata'] = get_metadata(cache['record'])
        except KeyError:
            cache['record'] = {
                'hash': 'nothing',
                'date': '2200-03-01'
            }
            cache['metadata'] = {
                'object_url': 'TODO',
                'large_thumbnail_url': 'TODO',
                'landing_url': 'TODO',
                'display_content_partner': 'TODO',
                'title': 'TODO'
            }

    return cache


def format_response(record, metadata):
    """
    Generates all variables that will be passed to the template.
    """

    day_date = datetime.strptime(record['date'], '%Y-%m-%d').date()

    if metadata['object_url'] is not None:
        image = metadata['object_url']
    else:
        image = metadata['large_thumbnail_url']

    return {
        'readable_date': day_date.strftime('%d %B %Y'),
        'record': {
            'image': image,
            'url': metadata['landing_url'],
            'author': metadata['display_content_partner'],
            'title': metadata['title'],
            'permalink': '/record/' + record['hash']
        },
        'calendar': get_calendar()
    }

@@ -1336,18 +1336,63 @@
 ': '
-2200-03-01
+3320-05-04',%0A                'date_current_year': '3320
 '%0A  
@@ -1460,36 +1460,32 @@
  'object_url': '
-TODO
 ',%0A             
@@ -1503,36 +1503,32 @@
 humbnail_url': '
-TODO
 ',%0A             
@@ -1542,28 +1542,25 @@
 ding_url': '
-TODO
+/
 ',%0A         
@@ -1594,20 +1594,16 @@
 tner': '
-TODO
 ',%0A     
@@ -1627,12 +1627,30 @@
 ': '
-TODO
+Not much to show today
 '%0A  

Tweak stub content