#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import sys
import dbf
import tempfile
import encodings
import time
from jinja2 import Template
from BeautifulSoup import BeautifulSoup as bs

class DurationException(Exception):
    """ """

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
                description='Convert dbf file to html.')
    parser.add_argument(
        'src_file',
        metavar='src-file',
        help='path to dbf file')
    params = parser.parse_args()

    #dbf module needs a file with extension
    with tempfile.NamedTemporaryFile(suffix=".dbf", mode="w+b") as tmp:
        data = open(params.src_file, 'rb').read()
        tmp.file.write(data)
        tmp.file.flush()
        table = dbf.Table(tmp.name).open()
        table.use_deleted = False
        attrs = table.field_names
        records = []
        start = time.time()
        limited = False
        try:
            for record in table:
                tmp = []
                for attr in attrs:
                    try:
                        value = unicode(record[attr])
                    except UnicodeDecodeError as err:
                        table._meta.decoder = encodings.codecs.latin_1_decode
                        value = unicode(record[attr])
                    except ValueError as err:
                        pass
                    tmp.append(value.strip())
                records.append(tmp)
                duration = time.time() - start
                if duration>=0.01:
                    raise DurationException() #limit extraction to 1/10 sec
        except DurationException:
            limited = True

        template = Template(
                    '<!DOCTYPE html>'
                    '<html lang="en">'
                       '<head>'
                         '<meta charset="utf-8">'
                         '<title>Display as HTML</title>'
                       '</head>'
                       '<body>'
                       '{% if limited %}'
                       '<p>WARNING: Limited to {{ records|length }} records.</p>'
                       '{% endif %}'
                         '<table border="1">'
                           '<tr>'
                               '{% for name in field_names %}'
                                   '<th>{{ name }}</th>'
                               '{% endfor %}'
                           '</tr>'
                             '{% for row in records %}'
                               '<tr>'
                                 '{% for value in row %}'
                                   '<td>{{ value }}</td>'
                                 '{% endfor %}'
                               '</tr>'
                             '{% endfor %}'
                         '</table>'
                       '</body>'
                    '</html>')
        output = template.render(
                    field_names=attrs,
                    records=records,
                    limited=limited)
        pretty_output = bs(output).prettify()
        sys.stdout.write(pretty_output)
