#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Desc:    This file is part of the ecromedos Document Preparation System
# Author:  Tobias Koch <tobias@tobijk.de>
# License: MIT
# URL:     http://www.ecromedos.net
#

import os, sys, getopt, tempfile

# make ecromedos relocatable
ECMDS_INSTALL_DIR = os.path.normpath(
        os.path.dirname(
            os.path.realpath(sys.argv[0])
        ) + os.sep + ".." )

sys.path.insert(1, ECMDS_INSTALL_DIR + os.sep + 'lib')

from net.ecromedos.version import VERSION
from net.ecromedos.error import ECMDSError, ECMDSPluginError
from net.ecromedos.ecmlprocessor import ECMLProcessor
import net.ecromedos.templates as document_templates

# exit values
ECMDS_ERR_INVOCATION = 1
ECMDS_ERR_PROCESSING = 2
ECMDS_ERR_UNKNOWN    = 3

def printVersion():
    """Display version information."""

    print("ecromedos Document Processor, version %s" % VERSION                           )
    print("Copyright (C) 2005-2016, Tobias Koch <tobias@tobijk.de>                      ")
#end function

def printUsage():
    """Display usage information."""

    print("                                                                             ")
    print("Usage: ecromedos [OPTIONS] <sourcefile>                                      ")
    print("                                                                             ")
    print("Options:                                                                     ")
    print("                                                                             ")
    print(" --help, -h            Display this help text and exit.                      ")
    print(" --basedir, -b <dir>   Use an alternative base directory from where to look  ")
    print("                       up the transformation rules.                          ")
    print(" --config, -c <file>   Use an alternative configuration file.                ")
    print(" --format, -f <format> Generate the specified output format                  ")
    print("                       (html or lualatex).                                  ")
    print(" --new, -n <doctype>   Start a new document of given doctype                 ")
    print("                       (article, book or report).                            ")
    print(" --style, -s <file>    Use an alternative style definition file.             ") 
    print(" --version, -v         Print version information and exit.                   ")
    print("                                                                             ")
    print(" --draft               Don't generate glossary or keyword indexes, which can ")
    print("                       save substantial amounts of time.                     ")
    print(" --finedtp             Activate pedantic typesetting, this can result in     ")
    print("                       overful horizontal boxes.                             ")
    print(" --nohyperref          Disable active links in PDF output.                   ")
    print(" --novalid             Skip validation of the document.                      ")
    print(" --tidy                Run HTML output through tidy (html only).            ")
#end function

def parseCmdLine():
    """Parse and extract arguments of command line options."""

    options = {}

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hvn:f:s:b:c:",
            ["help", "basedir=", "config=", "format=", "new=", "style=",
                "draft", "finedtp", "nohyperref", "novalid", "tidy", "version"])
    except getopt.GetoptError as e:
        msg  = "Error while parsing command line: %s\n" % e.msg
        msg += "Type 'ecromedos --help' for more information."
        raise ECMDSError(msg)
    #end try

    params = options.setdefault("xsl_params", {})

    for o, v in opts:
        if o == "--draft":
            params["global.draft"] = "'yes'"
        elif o == "--finedtp":
            params["global.lazydtp"] = "'no'"
        elif o in [ "--help", "-h" ]:
            printVersion()
            printUsage()
            sys.exit(0)
        elif o == "--nohyperref":
            params["global.hyperref"] = "'no'"
        elif o == "--novalid":
            options["do_validate"] = False
        elif o == "--tidy":
            options["do_tidy"] = True
        elif o in ["--basedir", "-b"]:
            options["style_dir"] = v
        elif o in ["--config", "-c"]:
            options["config_file"] = v
        elif o in ["--format", "-f"]:
            options["target_format"] = v.lower()
        elif o in ["--new", "-n"]:
            startDoc(v)
            sys.exit(0)
        elif o in ["--style", "-s"]:
            if not os.path.isfile(v):
                msg = "Style definition file '%s' not found." % v
                raise ECMDSError(msg)
            else:
                v = os.path.abspath(v)
            #end if
            params["global.stylesheet"] = "document('%s')" % v
        elif o in ["--version", "-v"]:
            printVersion()
            sys.exit(0)
        else:
            msg = "Unrecognized option '%s'.\n" % (o,)
            msg += "Type 'ecromedos --help' for more information."
            raise ECMDSError(msg)
        #end ifs
    #end while
    
    return options, args
#end function

def startDoc(doctype):
    """Outputs a template for a new document of "doctype" to stdout."""

    if not hasattr(document_templates, doctype):
        msg = "No template available for doctype '" + doctype + "'."
        raise ECMDSError(msg)
    else:
        template = document_templates.__dict__[doctype]
    #end if

    sys.stdout.write(template)
    sys.stdout.flush()
#end function

if __name__ == "__main__":
    try:
        # SETUP
        try:
            options, files = parseCmdLine()
            if len(files) < 1:
                msg = "ecromedos: no source file specified"
                raise ECMDSError(msg)
            if not os.path.isfile(files[0]):
                msg = "ecromedos: '%s' doesn't exist or is not a file"\
                    % files[0]
                raise ECMDSError(msg)
            #end ifs
        except ECMDSError as e:
            sys.stderr.write(e.msg() + "\n")
            sys.exit(ECMDS_ERR_INVOCATION)
        #end try

        # TRANSFORMATION
        try:
            with tempfile.TemporaryDirectory(prefix="ecmds-") as tmp_dir:
                # MAKE THE PROCESSOR USE THE TMPDIR CONTEXT
                options["tmp_dir"] = tmp_dir

                # SET INSTALLATION PATH
                options.setdefault("install_dir", ECMDS_INSTALL_DIR)

                # DO DOCUMENT TRANSFORMATION
                ECMLProcessor(options).process(files[0])
            #end with
        except ECMDSError as e:
            sys.stderr.write(e.msg() + "\n")
            sys.exit(ECMDS_ERR_PROCESSING)
    except KeyboardInterrupt:
        sys.stdout.write("\n -> Caught SIGINT, terminating.\n")
#end __main__
