#!/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)
#     31-Mar-2022, A. Le        (anle)
#         Use dirname to get parent directory in local mode
#         Rename reports directory to doc
#         Rename out directory to log
#     22-Mar-2022, A. Le        (anle)
#         Add option to read JSON from local directory
#
# ==============================================================
#
import argparse
import io
import os
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

template_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates')
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(template_dir)
)

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')
group = arg_parser.add_mutually_exclusive_group(required=True)
group.add_argument('-f', '--facility', help='Specify facility on which to read autocheckout JSON files')
group.add_argument('-j', '--json-dir',
                   help='Read JSON from directory (default: $MGNT_REPORT/data 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)
if args.json_dir:
    json_dir = args.json_dir
else:
    json_dir = '$MGNT_REPORT/data'

data_file_glob = os.path.join(json_dir, '{}.json'.format(element_filter))
data_file_list = agent.ls_basenames(data_file_glob)
if not data_file_list:
    print 'Error: no magnets matching "{}"'.format(args.element)
    sys.exit(1)

# get user information
user_name = agent.get_full_name()

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

for json_file in data_file_list:
    # generate dictionary for report
    checkout_structure = AutoCheckoutStructure()
    checkout_data = AutoCheckoutData(args.facility, args.json_dir)
    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')

    # 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
    log_dir = os.path.join(temp_dir, 'log')
    os.mkdir(log_dir)
    subprocess.call(['pdflatex', '--output-directory=' + log_dir, latex_path])

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

    # move doc, latex, and log to remote server
    if args.facility:
        parent_dir = os.path.dirname(json_dir)
    else:
        parent_dir = os.path.abspath(os.path.join(json_dir, os.pardir))

    agent.rsync_to_remote(temp_dir + '/', parent_dir + '/')

    # delete temporary directory
    shutil.rmtree(temp_dir)
