# macros

import sys
import os.path

# Ugly hack for local installations
htmlgen = sys.modules['mege.htmlgen']
htmlfunc = sys.modules['mege.htmlfunc']
import mege.git as git
import mege.misc as misc


def list_pages(pathdir=None):
    pathdir = misc.macrog('pathdir', pathdir)
    dl = htmlfunc.DefList()
    fs = [(p if os.path.isfile(p) else os.path.join(
                    p, 'index.org'), f, f[:-4] if os.path.isfile(p) else f + '/') for p, f in filter(
            lambda pf: (os.path.isfile(pf[0]) and pf[0].endswith('.org') and
                       pf[1] != 'index.org') or (
                os.path.isdir(pf[0]) and os.path.isfile(os.path.join(pf[0], 'index.org'))),
            ((os.path.join(pathdir, f), f) for f in os.listdir(pathdir)))]
    fs.sort(key=lambda pf: git.rr.get_last_modified_date(pf[0])[0] or
            misc.utcwhenmodified(pf[0]))
    for p, f, l in fs[::-1]:
        a = htmlgen.org_to_abstract(p, isfile=True, only_metadata=True)
        dl.add_item(htmlfunc.link(l, a.title), a.summary if a.summary
                    else None) #'No summary.')
    return dl.generate_html()

def titlelink(path, pathdir=None):
    pathdir = misc.macrog('pathdir', pathdir)
    orgpath = misc.get_org_path(os.path.join(pathdir, path))
    if orgpath:
        a = htmlgen.org_to_abstract(orgpath, isfile=True, only_metadata=True)
        title = a.title
    else:
        title = path
    return htmlfunc.link(path, title).generate_html()
