from docxtpl import DocxTemplate
import sys
from argparse import ArgumentParser
from reportsjob import ReportJobError, docxtemplateengine, htmltemplateengine
from pathlib import Path


def main():
    parser = ArgumentParser(prog='python docxtemplatecli.py')
    parser.add_argument('docxtemplate', type=str, help="The template file full path")
    parser.add_argument('datafile', type=str, help="JSON data file full path")
    parser.add_argument('--output-format', type=str, default='pdf', help="--output-format can be docx, html, pdf (default pdf)")
    parser.add_argument('--output', type=str, default='output', help="Folder where generate all the output files (default output)")
    params = parser.parse_args()

    datafile_path: Path = Path(params.datafile)
    if not datafile_path.is_file():
        raise ReportJobError("DataFile not found [{}]".format(params.datafile))
    generated_file_list = []
    if params.output_format == 'docx':
        generated_file_list = docxtemplateengine.run(params.docxtemplate, params.datafile, params.output_format,
                                                     params.output)
    else:
        raise ReportJobError("Invalid output format")
    import json
    json_output = {
        "files": generated_file_list
    }
    print(json.dumps(json_output))


if __name__ == '__main__':
    main()
