#!/usr/bin/env python

import sys
import subprocess

from . import mpsconfigquery

__all__ = ['export']

html_header = """
<html>
<head>
<style>
body {
    font: 10px Monaco, Courier, monospace;
}
#content {
    margin: 2em 5em;
}
table {
    border-top:   2px solid black;
    border-bottom:2px solid black;
    border-collapse:collapse;
}

th {
    border-bottom: 1px solid black;
}

tr {
    text-align:center;
}

tr:nth-child(even) {
    background:#eef3ff;
}

td, th {
    white-space: nowrap;
    padding-left: 0.5em;
    padding-right: 0.5em;
}

td:nth-child(13n+1),
td:nth-child(13n+6),
td:nth-child(13n+7),
td:nth-child(13n+8),
td:nth-child(13n+12),
td:nth-child(13n+13)
{
    text-align:left;
}

</style>
</head>
<body>
<div id="content">
<table>
"""

html_footer = """
</table>
</div>
</body>
</html>
"""

def export(dbfile, path, verbose):
    """Write html file to path"""

    if verbose:
        print "Exporting HTML file to", path
    
    try:
        outfile = open(path, "w")
    except IOError, e:
        sys.stderr.write('Could not open "%s": %s\n' % (path, e.strerror))
        return 1
    
    outfile.write(html_header)
    outfile.flush()

    command = ('sqlite3', '-html', '-header', dbfile)
    p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=outfile)
    p.stdin.write(mpsconfigquery.link_node_channel_faults + " order by fault_number;")
    p.stdin.close()    
    p.wait()
    
    outfile.write(html_footer)
    outfile.close()

