#!/usr/bin/env python
# ==============================================================
#
#  Abs:   Script for compiling pdf reports from magnet auto-checkout data
#         based on https://web.archive.org/web/20121024021221/http://e6h.de/post/11/
#         and https://tug.org/tug2019/slides/slides-ziegenhagen-python.pdf
#
#  Name:  mgnt_generate_checkout_report
#
#  Usage: mgnt_generate_checkout_report [-h] [-f FACILITY] [-e ELEMENT]
#
#  Facility: SLAC Controls (Development)
#
#  Auth:  08-Nov-2021, A. Le    (anle)
# --------------------------------------------------------------
#  Mods: (Latest to oldest)
#     dd-mmm-yyyy, F. Lastname  (user)
#         Comment
#
# ==============================================================
#
import argparse
import io
import os
import pwd
import shutil
import subprocess
import sys
import tempfile

import jinja2
from dateutil import parser

from helpers.mgnt_facility_agent import FacilityAgent
from mgnt_auto_checkout_data import AutoCheckoutData
from mgnt_auto_checkout_structure import AutoCheckoutStructure

latex_jinja_env = jinja2.Environment(
    block_start_string='\BLOCK{',
    block_end_string='}',
    variable_start_string='\VAR{',
    variable_end_string='}',
    comment_start_string='\#{',
    comment_end_string='}',
    line_statement_prefix='%-',
    line_comment_prefix='%#',
    trim_blocks=True,
    autoescape=False,
    loader=jinja2.FileSystemLoader(os.path.abspath('templates'))
)

latex_escapes = {
    '\n': '\\newline ',
    'red<<': '\\textcolor{Red}{',
    '>>': '}',
    '$': '\\$',
    '_': '\\_',
    '%': '\\%',
    '#': '\\#'
}


def escape_latex(data):
    escaped_data = data
    for char, escaped_char in latex_escapes.items():
        escaped_data = escaped_data.replace(char, escaped_char)

    return escaped_data


latex_jinja_env.filters['escape_latex'] = escape_latex

# Parse arguments
arg_parser = argparse.ArgumentParser(description='Generate pdf report of magnet autocheckout')
arg_parser.add_argument('-f', '--facility', help='Check out magnets in specified facility')
arg_parser.add_argument('-e', '--element', help='Generate report for specified element (ALL for all magnets)')
if len(sys.argv) == 1:
    arg_parser.print_help()
    arg_parser.exit()

args = arg_parser.parse_args()

# Get data for specified element(s)
if args.element == 'ALL':
    element_filter = '*'
else:
    element_filter = args.element

agent = FacilityAgent(args.facility)
data_file_list = agent.ls_basenames('$MGNT_REPORT/data/{}.json'.format(element_filter))
if not data_file_list:
    print 'Error: no magnets matching "{}"'.format(args.element)
    sys.exit(1)

for json_file in data_file_list:
    # generate dictionary for report
    checkout_structure = AutoCheckoutStructure()
    checkout_data = AutoCheckoutData(args.facility)
    checkout_data.load_json(json_file)
    report_dict = checkout_structure.generate_report_dict(checkout_data)

    # process json data
    for section in report_dict['sections']:
        for subsection in section['subsections']:
            for test in subsection['tests']:
                if test['status'] is None:
                    test['status'] = 'N/A'
                elif test['status']:
                    test['status'] = '\\textcolor{Green}{PASS}'
                else:
                    test['status'] = '\\textcolor{Red}{FAIL}'

                test_datetime = parser.parse(test['datetime'])
                test['date'] = test_datetime.strftime('%m/%d/%y')

    # get user information
    user_info = pwd.getpwuid(os.getuid())
    user_name = user_info.pw_gecos

    # load template from file
    template = latex_jinja_env.get_template('mgnt_report_template.tex')

    # combine template and variables
    document = template.render(element=report_dict['element'], device=report_dict['device'], name=user_name,
                               sections=report_dict['sections'])

    # create temporary directory
    temp_dir = tempfile.mkdtemp()

    # write document to latex
    latex_file = '{}.tex'.format(report_dict['element'])
    latex_dir = os.path.join(temp_dir, 'latex')
    latex_path = os.path.join(latex_dir, latex_file)
    os.mkdir(latex_dir)
    with io.open(latex_path, mode='w', encoding='utf-8') as f:
        f.write(document)

    # create pdf from latex
    out_dir = os.path.join(temp_dir, 'out')
    os.mkdir(out_dir)
    subprocess.call(['pdflatex', '--output-directory=' + out_dir, latex_path])

    # move pdf to reports directory
    pdf_file = '{}.pdf'.format(report_dict['element'])
    pdf_path = os.path.join(out_dir, pdf_file)
    reports_dir = os.path.join(temp_dir, 'reports')
    dest_pdf_path = os.path.join(reports_dir, pdf_file)
    os.mkdir(reports_dir)
    shutil.move(pdf_path, dest_pdf_path)

    # move pdf, tex, and log to remote server
    agent.rsync_to_remote(temp_dir + '/', '$MGNT_REPORT/')

    # delete temporary directory
    shutil.rmtree(temp_dir)
