#!/usr/bin/env python

import os

images = []
newimages = []
descriptions = []
title = None
intro = None
locn = None

TAB = "{}\t{}\n"

# open any existing details file and parse the contents
try:
    with open("details.txt", "r") as fh:
        for line in fh.readlines():
            if line[0:1] != "#":
                (type, detail) = line.strip().split("\t")
                if (type == "title"):
                    title = detail
                elif (type == "intro"):
                    intro = detail
                elif (type == "locn"):
                    locn = detail
                else:
                    images.append(type)
                    descriptions.append(detail)
except:
    pass

# generate a list of images
files = [f for f in os.listdir('.') if os.path.isfile(f) and f.endswith("-m.jpg")]
for f in files:
    f = f.replace("-m.jpg", "")
    if not f in images:
        newimages.append(f)

# create the details file, adding any new images that weren't there before at the end
with open("details.txt", "w") as out:
    out.write(TAB.format("title", title))
    out.write(TAB.format("intro", intro))
    for i in range(0, len(images)):
        out.write(TAB.format(images[i], descriptions[i]))

    if len(newimages) > 0 and len(images) > 0:
        out.write("#\n# new images\n#\n")

    for extra in newimages.sort():
        out.write(TAB.format(extra, ""))
    