#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pathlib import Path
import xmltodict

sups = ["InstrumentSetup", "DetectorSetup", "TelescopeSetup", "TipTiltCtrlSetup" , "InfoSetup"]
path = "../templates/"

info =  """
% This file was generated using the python script {}
% include it into the main tex file,
% then pdflatex the main tex file""".format(__file__)

def xml_file_to_dict(filename):

    try:
        with open(filename) as xml_file:
            xml_string = xml_file.read()
        return xmltodict.parse(xml_string)
    except IOError as e:
        {"description":"No description"}
        #raise e

def schema_table(schema, indent=8):

    ind = " "*indent

    print("\n")
    print(1*ind + "\\begin{description}")
    for x in sorted(schema['xs:schema']['xs:simpleType'], key=lambda d: d['@name']):
        anno = 'xs:annotation'
        if anno in x:
            name = x['@name'].replace("_Type","")
            info = x[anno]['xs:appinfo']
            doc = x[anno]['xs:documentation']['#text']
            print(1*ind + "  \\item[" + name +"] "+ info + " \\\\ "+ doc + " ")

            if 'xs:restriction' in x:
                if 'xs:enumeration' in x['xs:restriction']:
                    print("Allowed options for this parameters are:")
                    print("\\begin{itemize}")
                    try:
                        for v in sorted(x['xs:restriction']['xs:enumeration'], key=lambda d: d['@value']):
                            print("  \\item " + v["@value"] )
                    except TypeError as e:
                        print("\\item No named positions. ")
                    print("\\end{itemize}")
                    
    print(1*ind + "\\end{description}")


def parameters_table(ob, ref, sup, indent=10):

    ind = " "*indent

    #print(1*ind + "\\begin{table}[h]")
    print(1*ind + "\\begin{tabular}{p{6cm}lp{4cm}}")
    print(1*ind + "\\toprule")
    print(1*ind + " Parameter & Hidden & Value \\\\")

    if sup in ob and ob[sup]:
        print(1*ind + "\\midrule")
        for key, value in sorted(ob[sup].items()):
            print(1*ind + "  " + key + " & NO & \\texttt{" + str(value) + "} \\\\")

    if sup in ref and ref[sup]:
        print(1*ind + "\\midrule")
        for key, value in sorted(ref[sup].items()):
            print(1*ind + "  " + key + " & YES & \\texttt{" + str(value) + "} \\\\")

    print(1*ind + "\\bottomrule")
    print(1*ind + "\\end{tabular}")
    #print(1*ind + "\\end{table}")


def section_from_schema(sch, indent=2):

    ind = " "*indent

    print("\n" + ind + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
    print(       ind + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
    print(ind + "\\section{ \\texttt{" + sch + " } }")

    sch_xml = xml_file_to_dict(path+"schema/" + sch + ".xsd")
    schema_table(sch_xml)

    
def section_from_template_name(tpl, indent=2):

    ind = " "*indent

    print("\n" + ind + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
    print(       ind + "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
    print(ind + "\\section{ \\texttt{" + tpl + " } }")

    ref_xml = xml_file_to_dict(path+"ref/" + tpl + ".ref")
    ob_xml = xml_file_to_dict(path+"ob/" + tpl + ".xml")
    doc_xml = xml_file_to_dict(path+"doc/" + tpl + ".doc")
    tpl = path+"tpl/" + ref_xml["ReferenceSetup"]["Script"] + ".py"
    
    # Description of the template

    print("Based on \\texttt{" + ref_xml["ReferenceSetup"]["Script"] + "} python script.\\\\")
    
    
    if doc_xml:
        print(doc_xml["doc"]["description"]+"\\\\")

    print("\\textbf{Relevant script comments:}")
    print("\\begin{itemize}")
    try:
        with open(tpl) as f:
            for ln in f:
                ln = ln.strip()
                if ln.startswith("#") and ln.endswith("#"):
                    if not "#####" in ln.strip():                        
                        print("\\item \\texttt{" + ln.replace("#", "") + "} ")
                        
    except IOError as e:
        print("\\item \\texttt{No "+ tpl + " found!} \\\\")
        
    print("\\end{itemize}")

    # Table of parameters
    print("\n" + 3*ind + "\\subsection{Parameters table}")

    for sup in sups:

        print("\n" + 4*ind + "\\subsubsection{"+sup+"}")
        ob = ob_xml["ObservationBlock"]["Template"]
        ref = ref_xml["ReferenceSetup"]

        parameters_table(ob, ref, sup)


if __name__ == "__main__":
    
    import sys

    ###################################################
    
    orig_stdout = sys.stdout
    f = open('parameters_description.tex', 'w')
    sys.stdout = f
    
    filenames = Path(path+"schema/").glob("*Setup.xsd")

    print(info)
    for filename in filenames:
        section_from_schema(filename.stem)
    print(info)

    sys.stdout = orig_stdout
    f.close()
    
    ###################################################
    
    orig_stdout = sys.stdout
    f = open('template_parameters.tex', 'w')
    sys.stdout = f
        
    filenames = Path(path+"ref/").glob("SHARKNIR*ref")

    print(info)
    for filename in sorted(filenames):
        section_from_template_name(filename.stem)
    print(info)

    sys.stdout = orig_stdout
    f.close()
