#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
import os
import re
import sys
import collections

def get_file_doc(filename):
    '''Return all documentation of a IDL .pro file in one string. 

    Documentation is included between the ";+" and ";-" lines as comment.
    Additionally, a FILE section is included.
    '''
    indent_regexp = re.compile('(\s*)(\S.*)')
    with open(filename) as sfile:
        docstring = ''
        indent = None
        in_doc = False
        rst = False
        for line in sfile:
            l = line.replace('\r','').split(';',1)
            if len(l) > 1:
                c = l[1][:-1].expandtabs()
                if c.startswith('+'):
                    in_doc = True
                elif c.startswith('-'):
                    in_doc = False
                elif "docformat = 'rst'" in c:
                    rst = True
                elif in_doc:
                    if indent is None:
                        indent = len(indent_regexp.match(c).groups()[0])
                    docstring += c[indent-len(c[:indent].strip()):] + '\n'
        return docstring, rst

def get_sections(doc, rst = False):
    indent_regexp = re.compile('(\s*)(\S.*)')
    indent = None
    sections = collections.OrderedDict()
    if rst:
        s = 'Description'
        sections[s] = ''
    for l in doc.splitlines():
        if len(l.strip()) == 0:
            continue
        if not l.startswith(' ') and not rst:
            c = l.split(':', 1)
            s = c[0]
            sections[s] = c[1] if len(c) > 1 else '' 
            indent = None
        elif l.strip().startswith(':') and rst:
            s = l.strip().replace(':','')
            sections[s] = ''
            indent = None
        else:
            if indent is None:
                indent = len(indent_regexp.match(l).groups()[0])
            sections[s] += l[indent:] + '\n'
    return sections

def to_html(sections):
    s = '\n'.join(
        '<dl>\n<dt>{section}</dt>\n<dd><pre>\n{doc}</pre></dd>\n</dl>\n'\
        .format(section = section, doc = doc)
        for section, doc in sections.items())
    return s

category_synonyms = {
    'File I/O': 'FileIO',
    'File IO': 'FileIO',
    'Utilites':'Utilities',
    'Utility':'Utilities',
    'Maps':'Map Utilities',
    'Map Projection':'Map Projections',
    'General':'General Programming',
    'General programming':'General Programming',
    'math':'Mathematics',
    'Math':'Mathematics',
    'graphics':'Graphics',
    'Object Graphics':'Graphics',
    'IDL Object Graphics':'Graphics',
    'Graphics Programs':'Graphics',
    'Graphics Utility':'Graphics',
    'Widgets':'Widget Programming',
    'Utility routine for FSC_PSCONFIG__DEFINE':'General Programming',
    'Color Specification See related program cgCOLOR':'Graphics',
    'Gridding':None,
    'Color':None,
    'Analysis':None,
    'Obejct Programming':None,
    'Object Programming':None,
}

html_template = '''<html>
<head>
  <TITLE>{package}: {NAME}</TITLE>
  <style>
dt {{font-weight: bold;}}
  </style>
</head>
<body>
  <H1><a href="index.html">{package}</a>: {NAME}</H1>
  <ul>
  {categories}
    <li><a href="/usr/share/gnudatalanguage/{package}/{name}.pro">[Source code]</a></li>
  </ul>
  {doc}
</body>
</html>
'''

os.mkdir('html')
files = list()
for l in open('debian/install').readlines():
    files += glob.glob(l.split()[0])

index = dict()
for filename in files:
    print filename
    if not filename.endswith('.pro'):
        continue
    name = filename[:-4]
    try:
        doc, rst = get_file_doc(filename)
    except:
        continue
    sections = get_sections(doc, rst)
    category = sections.get('Categories', sections.get('CATEGORY'))
    categories = []
    if category is not None:
        for c in category.split(','):
            c = c.strip().replace('.', '')
            c = category_synonyms.get(c, c)
            if c is None:
                continue
            categories.append(c)
            index.setdefault(c, list()).append(name)
    with open(os.path.join('html', name + '.html'), 'w') as html_file:
        html_file.write(html_template.format(
            package = 'coyote',
            categories = '\n'.join('<li><a href={fname}.html>coyote/{cat}</a></li>'.format(cat = c, fname = c.replace(' ', '_'))
                                   for c in categories),
            name = name,
            NAME = name.upper(),
            doc = to_html(sections)))

html_template = '''<html>
<head>
  <TITLE>{package}/{category}: List of routines</TITLE>
</head>
<body>
  <H1><a href="index.html">{package}</a>/{category}</H2>
  <table>
{list}    
  </table>
</body>
</html>
'''
for category, procedures in index.items():
    print category
    with open(os.path.join('html', category.replace(' ','_')+'.html'), 'w') as html_file:
        s = '\n'.join(
            '    <tr><td><a href="{proc}.html">{PROC}</a></td><td>{desc}</td></tr>'.format(
                proc=proc,
                PROC=proc.upper(),
                desc = '')
            for proc in procedures)
        html_file.write(html_template.format(
            package = 'coyote',
            category = category,
            list = s))
 

html_template = '''<html>
<head>
  <TITLE>{package}: List of categories</TITLE>
</head>
<body>
  <H1>{package}</H1>
  <H2>List of categories</H2>
  <table>
{list}    
  </table>
</body>
</html>
'''
with open(os.path.join('html', 'index.html'), 'w') as html_file:
    categories = list(index.keys())
    categories.sort()
    s = '\n'.join(
        '    <tr><td><a href="{fname}.html">{category}</a></td><td></td></tr>'
        .format(category = category, fname=category.replace(' ', '_'))
        for category in categories)
    html_file.write(html_template.format(
        package = 'coyote',
        list = s))

