#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
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 get_sections(doc):
    indent_regexp = re.compile('(\s*)(\S.*)')
    indent = None
    sections = dict()
    for l in doc.splitlines():
        if len(l.strip()) == 0:
            continue
        if not l.startswith(' '):
            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(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}: {NAME}</TITLE>
  <style>
dt {{font-weight: bold;}}
  </style>
</head>
<body>
  <H1><a href="index.html">{package}</a>: {NAME}</H1>
  <p>
    <a href="/usr/share/gnudatalanguage/{package}/{name}.pro">[Source code]</a>
  </p>
  {doc}
</body>
</html>
'''

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

index = list()
for filename in files:
    print filename
    if not filename.endswith('.pro'):
        continue
    name = filename[:-4]
    try:
        doc = get_file_doc(filename)
    except:
        continue
    index.append((name, get_sections(doc)['PURPOSE']))
    with  open(os.path.join('html', name + '.html'), 'w') as html_file:
        html_file.write(html_template.format(
            package = 'mpfit',
            name = name,
            NAME = name.upper(),
            doc = to_html(doc)))


html_template = '''<html>
<head>
  <TITLE>{package}: List of procedures</TITLE>
</head>
<body>
  <H1>{package}</H1>
    <ul>
      <li><a href='fitqa.html'>Frequently Asked Questions</a></li>
      <li><a href='mpfittut.html'>Tutorial: 1D Curve Fitting in IDL using MPFITFUN and PFITEXPR</a></li>
    </ul>
  <H2>List of procedures</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="{proc}.html">{PROC}</a></td><td>{desc}</td></tr>'.format(
            proc = proc,
            PROC = proc.upper(),
            desc = desc)
        for proc, desc in index)
    html_file.write(html_template.format(
        package = 'mpfit',
        list = s))

