#! /usr/bin/env python

import argparse
import subprocess
import sys
import os
from typing import List, Union

def cmdExecute(command: List[str], verbose = False, head_msg: Union[str,None] = None ,msg: Union[str,None] = None):
    msg = msg or " ".join(command)
    head_msg = head_msg or "cmd execute: "
    if verbose:
        print(head_msg, msg)
    p = subprocess.run(command)
    p.check_returncode()

def updateIssue(issuePath: str, verbose = False):
    cmd = ["deno", "run","--no-check", "-A","tools/getIssue.ts", "--path",issuePath]
    cmdExecute(cmd, verbose, "update issue:")

def printDocument(issuePath:str, outDir:str, watch = False, verbose = False):
    if verbose:
        print("build document : issuePath(", issuePath, ") to ", outDir)
    cmd = ["deno", "run","--no-check" ,"-A","tools/printDocument.ts", "--issue_path", issuePath, "--outDir", outDir]
    if watch:
        cmd.append("--watch")
    p = subprocess.run(cmd)
    p.check_returncode()

def build(args):
    parser = argparse.ArgumentParser(description='Compiling the documentation', prog="cli.py build")
    parser.add_argument('-v', '--verbose', action='store_true', help='verbose mode')
    parser.add_argument('--update_issues', action='store_true', help='update issues')
    parser.add_argument('--outDir', default="build", help='output directory')
    parser.add_argument('-w', '--watch', action='store_true', help='watch for changes')

    args = parser.parse_args(args)
    if args.verbose:
        print("build start")

    issuePath = os.path.join(args.outDir,"issues.json")
    if args.update_issues:
        updateIssue(issuePath, args.verbose)
    printDocument(issuePath, args.outDir, args.watch, args.verbose)
    cmd = ["mdbook", "build"]
    cmdExecute(cmd, args.verbose)

def serve(args):
    """serve the documentation and reload on changes"""
    parser = argparse.ArgumentParser(description='Serve the documentation and reload changes', prog="cli.py serve")
    parser.add_argument('-v', '--verbose', action='store_true', help='verbose mode')
    parser.add_argument('-p', '--port', default=3000, help='port')
    parser.add_argument('--update_issues', action='store_true', help='update issues')
    outDir = "build"
    issuePath = os.path.join(outDir,"issues.json")
    args = parser.parse_args(args)
    if args.verbose:
        print("serve start")
    cmd = ["mdbook", "serve", "--port", str(args.port)]
    p = subprocess.Popen(cmd)
    printDocument(issuePath, outDir, True, args.verbose)
    p.wait()
    if p.returncode != 0:
        sys.exit(p.returncode)

def help(_args):
    global commandList
    print("subcommands:")
    for command in commandList.keys():
        print("\t", command)

def issueUpdate(args):
    parser = argparse.ArgumentParser(description='Update issues', prog="cli.py issueUpdate")
    parser.add_argument('-v', '--verbose', action='store_true', help='verbose mode')
    parser.add_argument('--outDir', default="build", help='output directory')
    args = parser.parse_args(args)
    issuePath = os.path.join(args.outDir,"issues.json")
    updateIssue(issuePath, args.verbose)

def buildPdf(args):
    parser = argparse.ArgumentParser(description='Print to pdf', prog="cli.py buildPdf")
    parser.add_argument('-v', '--verbose', action='store_true', help='verbose mode')
    parser.add_argument('--outDir', default="build/doc.pdf", help='output directory')
    parser.add_argument('--browser-path', help='path to the browser')
    args = parser.parse_args(args)
    if os.path.exists(args.outDir):
        if args.verbose:
            print("remove old file")
        os.remove(args.outDir)

    absPath = os.path.normpath(os.path.join( os.getcwd(),'book' , 'print.html' )).replace('\\', '/')
    url = f"file://{absPath}"
    if args.verbose:
        print("build start")
        print("print url", url)
    cmd = ["deno", "run","--no-check","--unstable" ,"-A","tools/printPdf.ts", "--outDir", args.outDir, "--url", url]
    if args.browser_path:
        cmd.append("--chromeDir")
        cmd.append(args.browser_path)
    cmdExecute(cmd, args.verbose, "print pdf:")
    cmd = ["java", "-jar", "tools/pdfbox-app-2.0.26.jar", "PDFMerger", "cover.pdf", args.outDir, args.outDir]
    cmdExecute(cmd, args.verbose, "merge pdf:")

commandList = {
    'build': build,
    'help': help,
    'issueUpdate': issueUpdate,
    'serve': serve,
    'buildPdf': buildPdf
}

def main():
    args = sys.argv
    if len(args) < 2:
        print("no subcommand", file=sys.stderr)
        help(args)
        return
    _command = args[0]
    subCommand = args[1]
    if subCommand not in commandList:
        print("Command not found", file=sys.stderr)
        help(args)
        sys.exit(1)
    args = args[2:]
    os.makedirs("build", exist_ok=True)
    commandList[subCommand](args)

if __name__ == '__main__':
    main()