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

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
        for line in sfile:
            l = line.replace('\r','').split(';',1)
            if len(l) > 1:
                c = l[1][:-1].expandtabs()
                if c.__eq__('+'):
                    in_doc = True
                elif c.__eq__('-'):
                    in_doc = False
                elif in_doc:
                    if indent is None:
                        indent = len(indent_regexp.match(c).groups()[0])
                    docstring += c[indent:] + '\n'
        return docstring

def to_html(doc):
    indent_regexp = re.compile('(\s*)(\S.*)')
    s = '<dl>'
    indent = None
    for l in doc.splitlines():
        if len(l.strip()) == 0:
            continue
        if not l.startswith(' '):
            if indent is not None:
                s += '</pre></dd>\n'
            s += '<dt>{0}</dt>\n'.format(l.strip().replace(':',''))
            indent = None
        else:
            if indent is None:
                indent = len(indent_regexp.match(l).groups()[0])
                s += '<dd><pre>\n'
            s += l[indent:] + '\n'
    s += '</pre></dd>'
    return s
            
html_template = '''<html>
<head>
  <TITLE>{package}/{subpackage}: {NAME}</TITLE>
  <style>
dt {{font-weight: bold;}}
  </style>
</head>
<body>
  <H1><a href="index.html">{package}</a> / 
  <a href="{subid}.html">{subpackage}</a>:
  {NAME}</H1>
  <p>
    <a href="/usr/share/gnudatalanguage/{package}/{name}.pro">[Source code]</a>
  </p>
  {doc}
</body>
</html>
'''

os.mkdir('html')
content = open('contents.txt').readlines()
subpackage = None
name_re = re.compile('^([A-Z][A-Z_0-9]+)[^A-Za-z_0-9]+(.*)')
index = list()
subindex = dict()
where = None
for i in range(len(content)):
    if i < len(content)-1 and '________' in content[i+1]:
        subpackage, where = content[i].split(' in ')[:2]
        subpackage = subpackage.strip()
        where = where.strip().split(' ')[0].strip()
        where = where.split('/')[1]
        index.append((where, subpackage))
        subindex[where] = list()
        continue
    if '------' in content[i]:
        continue    
    g = name_re.match(content[i])
    if g is None:
        if where in subindex and len(subindex[where]) > 0:
            subindex[where][-1] = (subindex[where][-1][0],
                                   subindex[where][-1][1]
                                   + ' ' + content[i].strip())
        continue
    name = g.groups()[0].lower()
    desc = g.groups()[1].strip()
    filename = os.path.join('pro', name+'.pro')
    try:
        doc = get_file_doc(filename)
    except:
        continue
    subindex[where].append((name, desc))
    with  open(os.path.join('html', name + '.html'), 'w') as html_file:
        html_file.write(html_template.format(
            package = 'idlastro',
            subpackage = subpackage,
            subid = where,
            name = name,
            NAME = name.upper(),
            doc = to_html(doc)))

html_template = '''<html>
<head>
  <TITLE>{package}/{subpackage}: List of routines</TITLE>
</head>
<body>
  <H1><a href="index.html">{package}</a></H1>
  <H2>{subpackage}</H2>
  <table>
{list}    
  </table>
</body>
</html>
'''
for name, subpackage in index:
    print name
    with open(os.path.join('html', name+'.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 = desc)
            for proc, desc in subindex[name])
        html_file.write(html_template.format(
            package = 'idlastro',
            subpackage = subpackage,
            list = s))

html_template = '''<html>
<head>
  <TITLE>{package}: List of subpackages</TITLE>
</head>
<body>
  <H1>{package}</H1>
  <H2>List of subpackages</H2>
  <table>
{list}    
  </table>
</body>
</html>
'''
with open(os.path.join('html', 'index.html'), 'w') as html_file:
    s = '\n'.join(
        '    <tr><td><a href="{subpkg}.html">{SUBPKG}</a></td><td>{desc}</td></tr>'.format(
            subpkg = subpkg,
            SUBPKG = subpkg.upper(),
            desc = desc)
        for subpkg, desc in index)
    html_file.write(html_template.format(
        package = 'idlastro',
        list = s))

