#!/usr/bin/env python3

import os
import argparse
from verstak_parser import VDocument, Glue


def main(in_path: str, out_path: str, tipograf_enabled: bool, allow_header_links: bool, skip_tables: bool):
    if os.path.isdir(in_path):
        if not os.path.isdir(out_path):
            os.makedirs(out_path)
        print(f"Listing directory {in_path}")
        process_directory(in_path, out_path, tipograf_enabled, allow_header_links, skip_tables)
    elif os.path.isfile(in_path):
        if not os.path.isdir(out_path):
            os.makedirs(out_path)
        process_file(in_path, out_path, tipograf_enabled, allow_header_links, skip_tables)
    else:
        print(f"Error: {in_path} doesn't exist")


def process_file(in_path: str, out_path: str, tipograf_enabled: bool, allow_header_links: bool, skip_tables: bool):
    doc = os.path.basename(in_path)
    print(f"Started parsing {in_path}")
    document = VDocument.from_file(f"{in_path}")
    if tipograf_enabled:
        document.do_typograf()
    document.store_html(f"{out_path}{os.sep}{doc}.html", allow_header_links=allow_header_links, skip_tables=skip_tables)
    print(f"Finished parsing {in_path}")
    print(f"Output file: {out_path}{os.sep}{doc}.html")


def process_directory(in_path: str, out_path: str, tipograf_enabled: bool, allow_header_links: bool, skip_tables: bool):
    docs = os.listdir(in_path)
    i = 1
    for doc in docs:
        if not doc.startswith(".") and not doc.startswith("~") and doc.endswith("docx"):
            print(f"Started parsing  ({i}/{len(docs)}): {doc}")
            document = VDocument.from_file(f"{in_path}{os.sep}{doc}")
            if tipograf_enabled:
                document.do_typograf()
            document.store_html(f"{out_path}{os.sep}{doc}.html", allow_header_links=allow_header_links,
                                skip_tables=skip_tables)
            print(f"Finished parsing ({i}/{len(docs)}): {doc}")
        i += 1
    print(f"Done {in_path}")
    print(f"Files are stored in {out_path}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Make html from docx.',
                                     formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('input', metavar='in', type=str, nargs='?',
                        help='Input file/directory')
    parser.add_argument('output', metavar='out', type=str, nargs='?',
                        help='Output directory', default=f"{os.getcwd()}{os.sep}")
    parser.add_argument('-t', dest='tipograf_enabled', action='store_false',
                        help='Disable tipograf')
    parser.add_argument('-ah', dest='allow_header_links', action='store_true',
                        help='Allow links in headers/titles')
    parser.add_argument('-st', dest='skip_tables', action='store_true',
                        help='Print stub instead of parsed tables')
    parser.add_argument('--config', dest='config', action='store_true',
                        help='Show configs paths of tipograph currently in use\n'
                             'VERSTAK_CONFIG environment variable can include path\n'
                             'for additional configure file for tipograf')
    args = parser.parse_args()
    if args.config:
        print(f"Paths to configure files:")
        for config_path in Glue().configs_paths():
          print(config_path)
    elif args.input is None:
        parser.error("the following arguments are required: in")
    else:
        main(args.input, args.output, args.tipograf_enabled, args.allow_header_links, args.skip_tables)
