#!/usr/bin/env python

import os, sys, string, glob
import importlib
import plasTeX
from plasTeX.TeX import TeX
from plasTeX.Config import config
from plasTeX.ConfigManager import *
from plasTeX.Logging import getLogger, updateLogLevels

log = getLogger()

__version__ = '2.1'

def collect_renderer_config(config):
    plastex_dir = os.path.dirname(os.path.realpath(plasTeX.__file__))
    renderers_dir = os.path.join(plastex_dir, 'Renderers')
    renderers = next(os.walk(renderers_dir))[1]
    for renderer in renderers:
        try:
            conf = importlib.import_module('plasTeX.Renderers.'+renderer+'.Config')
        except ImportError as msg:
            continue

        config += conf.config

def main(argv):
    """ Main program routine """
    print('plasTeX version %s' % __version__)

    collect_renderer_config(config)

    # Parse the command line options
    try:
        opts, args = config.getopt(argv[1:])
    except Exception as msg:
        log.error(msg)
        print(config.usage())
        sys.exit(1)

    if not args:
        print(config.usage())
        sys.exit(1)

    file = args.pop(0)

    if config['logging']:
        updateLogLevels(config['logging'])

    # Create document instance that output will be put into
    document = plasTeX.TeXDocument(config=config)

    # Instantiate the TeX processor and parse the document
    tex = TeX(document, myfile=file)

    # Send log message to file "jobname.log" instead of console
    if config['files']['log']:
        tex.fileLogging()

    # Populate variables for use later
    if config['document']['title']:
        document.userdata['title'] = config['document']['title']
    jobname = document.userdata['jobname'] = tex.jobname
    cwd = document.userdata['working-dir'] = os.getcwd()

    # Load aux files for cross-document references
    pauxname = '%s.paux' % jobname
    rname = config['general']['renderer']
    for dirname in [cwd] + config['general']['paux-dirs']:
        for fname in glob.glob(os.path.join(dirname, '*.paux')):
            if os.path.basename(fname) == pauxname:
                continue
            document.context.restore(fname, rname)

    # Parse the document
    tex.parse()

    # Set up TEXINPUTS to include the current directory for the renderer
    os.environ['TEXINPUTS'] = '%s%s%s%s' % (os.getcwd(), os.pathsep,
                                         os.environ.get('TEXINPUTS',''), os.pathsep)

    # Change to specified directory to output to
    outdir = config['files']['directory']
    if outdir:
        outdir = string.Template(outdir).substitute({'jobname':jobname})
        if not os.path.isdir(outdir):
            os.makedirs(outdir)
        log.info('Directing output files to directory: %s.' % outdir)
        os.chdir(outdir)

    # Load renderer
    try:
        exec('from plasTeX.Renderers.%s import Renderer' % rname, globals())
    except ImportError as msg:
        log.error('Could not import renderer "%s".  Make sure that it is installed correctly, and can be imported by Python.' % rname)
        sys.exit(1)

    # Write expanded source file
    #sourcefile = '%s.source' % jobname
    #open(sourcefile,'w').write(document.source.encode('utf-8'))

    # Write XML dump
    if config['general']['xml']:
        outfile = '%s.xml' % jobname
        with open(outfile,'w',encoding='utf-8') as f:
            f.write(document.toXML())

    # Apply renderer
    Renderer().render(document)

    print

def info(type, value, tb):
   if hasattr(sys, 'ps1') or not sys.stderr.isatty():
      # we are in interactive mode or we don't have a tty-like
      # device, so we call the default hook
      sys.__excepthook__(type, value, tb)
   else:
      import traceback, pdb
      # we are NOT in interactive mode, print the exception...
      traceback.print_exception(type, value, tb)
      print
      # ...then start the debugger in post-mortem mode.
      pdb.pm()

#sys.excepthook = info

#sys.setrecursionlimit(10000)

#main(sys.argv)
try:
    main(sys.argv)
except KeyboardInterrupt:
    pass
