from collections import namedtuple
from json import loads as from_json
from pathlib import Path

'''
This plugin helps loading images for each section.
Images should be located at
    <static-folder>/<image-path>/<section-name>/<image-folder>

eg.
    static/image/section1/folder-for-my-image/
    static/image/section2/subsection/folder-for-another-image/
    ...

Each image folder should contain a file named `_metadata.json`
with the following information
    {
        "name": "<image-name>",
        "year": "<year>",
        "category": "<category-name>",
        "images": ["<main-image-name>", "<image-variant-1>", "<image-variant-2>", ...]
    }

Along with the image files which should be called
    <main-image-name>
    <image-variant-1>
    <image-variant-2>
    ...

'''

IMAGE_PATH = 'image' # relative to the static path
STATIC = ''

Image = namedtuple('Image', ['name', 'year', 'category', 'description', 'filenames'])

# Functions

def images(section):
    sec_path = Path(STATIC, IMAGE_PATH, section)
    for path in sec_path.iterdir():
        if path.name.startswith('_'):
            continue
        metafile = path.joinpath('_metadata.json')
        if metafile.exists():
            img_base = path.relative_to(STATIC)
            metadata = from_json(metafile.read_text())
            img = Image(
                metadata.get('name'),
                metadata.get('year'),
                metadata.get('category'),
                metadata.get('description'),
                [img_base.joinpath(img_name) for img_name in metadata.get('images', [])])
            print(img)
            yield img


def init_plugin(env, config):
    global STATIC
    STATIC = config['STATIC']
    env.globals['images'] = images
