#!/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

""")
    rowTemplate = string.Template(r"$$\Box$$ & $card & $channel & \texttt{$pv_prefix} & \texttt{$fault_name} \\")

    document_header_template = string.Template(r"""\documentclass[10pt, 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}{@{}cccll@{}}
\toprule
\multicolumn{1}{@{}c}{Verified} & \multicolumn{1}{c}{Card} & \multicolumn{1}{c}{Channel} & \multicolumn{1}{c}{PV Prefix} & \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@{}}{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

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

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

    outfile.close()



