#!/usr/bin/env python

import sys
import os
import string
import sqlite3

from . import mpsconfigquery

def escape(string):
    escaped = str(string)
    escaped = escaped.replace("$", r"\$")
    escaped = escaped.replace("_", r"\_")
    escaped = escaped.replace("&", r"\&")
    escaped = escaped.replace("%", r"\%")

    return escaped    

def export(cursor, path, rev_string='', embed_latex = False, verbose = False):
    """Write LaTeX file to path"""
    
    headerTemplate = string.Template(
r"""
\chapter{Link Node $lnid}%$lnhostname

""")
    row_format = r'$\Box$ & {0[card]} & {0[channel]} & \texttt{{{0[pv_prefix]}}} & \texttt{{{0[device_name]}}} & \texttt{{{0[fault_name]}}} \\'

    document_header_template = string.Template(r"""\documentclass[9pt, oneside]{book}
\usepackage{lcls-article}
\usepackage{longtable}

\newcommand\code{\begingroup \urlstyle{tt}\Url}
\renewcommand\revnum{$rev_string}

\title{MPS Link Node Inputs:\\$rev_string}
\date{}

\begin{document}

\maketitle

\addtocounter{page}{1}

\tableofcontents
""")
    
    document_footer = r"""\end{document}"""

    table_header = r"""
\begin{longtable}{@{}ccclll@{}}
\toprule
\multicolumn{1}{@{}c}{Verified} & \multicolumn{1}{c}{Card} & \multicolumn{1}{c}{Channel} & \multicolumn{1}{c}{PV Prefix} & \multicolumn{1}{c}{Device Name} & \multicolumn{1}{c@{}}{Fault Name} \\
\midrule
\endfirsthead


\multicolumn{5}{c}{\ldots continued from previous page} \\
\midrule
\multicolumn{1}{@{}c}{Verified} & \multicolumn{1}{c}{Card} & \multicolumn{1}{c}{Channel} & \multicolumn{1}{c}{PV Prefix} & \multicolumn{1}{c}{Device Name} & \multicolumn{1}{c@{}}{Fault Name} \\
\midrule
\endhead

\midrule
\multicolumn{5}{c}{{continued on next page\ldots}} \\
\endfoot

\bottomrule
\endlastfoot

"""

    table_footer = r"""
\end{longtable}
"""

    # Open new file
    try:
        outfile = open(path, 'w')
    except IOError, e:
        sys.stderr.write('Could not open "%s": %s\n' % (path, e.strerror))
        return 1
    
    if verbose:
        print "Exporting", path
    
    if not embed_latex:
        print >> outfile, document_header_template.substitute(rev_string = rev_string)

    # Write out the files
    lnid = None
    cursor.execute(mpsconfigquery.link_node_channel_faults + " order by link_node_id, card, channel")
    for row in cursor:
    
        if lnid != row['link_node_id']:            
            if lnid != None:
                print >> outfile, table_footer
            lnid = row['link_node_id']
            lnhostname = "---"
            print >> outfile, headerTemplate.substitute(lnid = lnid, lnhostname = lnhostname)
            print >> outfile, table_header

        values = {}
        values['card']        = escape(row['card'])
        values['channel']     = escape(row['channel'])
        values['device_name'] = escape(row['device_name'])
        values['fault_name']  = escape(row['fault_name'])
        values['pv_prefix']   = escape('{0[pv_device_type]}:{0[pv_area]}:{0[pv_position]}:{0[pv_attribute]}'.format(row))
        
        print >> outfile, row_format.format(values)

    print >> outfile, table_footer
    
    if not embed_latex:
        print >> outfile, document_footer

    outfile.close()



