#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
import os, sys
from subprocess import getstatusoutput
from doconce.sphinx import sphinx_dir
from doconce.jupyterbook import jupyterbook
from doconce.slides import slides_html, slides_beamer, slides_markdown
from doconce.misc import (
    misc_option,
    insertdocstr,
    spellcheck,
    capitalize,
    gwiki_figsubst,
    latin2html,
    remove_inline_comments,
    apply_inline_edits,
    sphinxfix_localURLs,
    old2new_format,
    latex_header,
    latex_footer,
    latex_problems,
    ref_external,
    find_nonascii_chars,
    replace_from_file,
    replace,
    subst,
    find,
    include_map,
    expand_mako,
    wildcard_notation,
    teamod,
    list_fig_src_files,
    list_labels,
    split_rst,
    split_html,
    html_colorbullets,
    md2html,
    md2latex,
    change_encoding,
    guess_encoding,
    clean,
    lightclean,
    remove_exercise_answers,
    remove,
    grab,
    ptex2tex,
    include_map,
    expand_commands,
    combine_images,
    latex_exercise_toc,
    pygmentize,
    makefile,
    latex2doconce,
    latex_dislikes,
    html2doconce,
    ipynb2doconce,
    fix_bibtex4publish,
    diff,
    gitdiff,
    csv2table,
    extract_exercises,
    linkchecker,
    grep,
    help_format
    )

commands = "help, format, find, subst, replace, remove, spellcheck, apply_inline_edits, capitalize, change_encoding, " \
           "clean, combine_images, csv2table, diff, expand_commands, expand_mako, extract_exercises, " \
           "find_nonascii_chars, fix_bibtex4publish, gitdiff, grab, grep, guess_encoding, gwiki_figsubst, html2doconce, " \
           "html_colorbullets, jupyterbook, include_map, insertdocstr, ipynb2doconce, latex2doconce, latex_dislikes, " \
           "latex_exercise_toc, latex_footer, latex_header, latex_problems, latin2html, lightclean, linkchecker, " \
           "list_fig_src_files, list_labels, makefile, md2html, md2latex, old2new_format, ptex2tex, pygmentize, " \
           "ref_external, remove_exercise_answers, remove_inline_comments, replace_from_file, slides_beamer, " \
           "slides_html, slides_markdown, sphinx_dir, sphinxfix_localURLs, split_html, split_rst, teamod".split(", ")

def help():
    _registered_commands = [
        ('%65s' % 'transform doconce file to another format', """doconce format html|latex|pdflatex|rst|sphinx|plain|gwiki|mwiki|\n               cwiki|pandoc|st|epytext dofile"""),

        (' '*29 + 'substitute a phrase by another using regular expressions (in this example -s is the re.DOTALL modifier, -m is the re.MULTILINE modifier, -x is the re.VERBOSE modifier, --restore copies backup files back again)',
            """doconce subst [-s -m -x --restore] regex-pattern \\ \n        regex-replacement file1 file2 ..."""),
        ('replace a phrase by another literally (exact text substitution)', """doconce replace from-text to-text file1 file2 ..."""),
        ('replace using from and to phrases from file', """doconce replace_from_file file-with-from-to-replacements file1 file2 ..."""),
        ('search for a (regular) expression in all .do.txt files in the current directory tree (useful when removing compilation errors)', """doconce find expression"""),
        ('print an overview of how various files are included in the root doc', """doconce include_map mydoc.do.txt"""),
        ('replace all mako function calls by the `results of the calls', """doconce expand_mako mako_code_file funcname file1 file2 ..."""),
        ('remove all inline comments in a doconce file', """doconce remove_inline_comments dofile"""),
        ('apply all edits specified through inline comments', """doconce apply_inline_edits"""),
        (' '*36 +   'create a directory for the sphinx format (requires sphinx version >= 1.1)',
            """doconce sphinx_dir copyright='John Doe' title='Long title' \\\n        short_title="Short title" version=0.1 intersphinx \\\n        /path/to/mylogo.png dofile"""),
        (' ' * 45 + 'split a sphinx/rst file into parts according to !split commands',
         """doconce format sphinx complete_file \ndoconce split_rst complete_file \ndoconce sphinx_dir complete_file \npython automake_sphinx.py"""),
        ('walk through a directory tree and insert doconce files as docstrings in *.p.py files', """doconce insertdocstr rootdir"""),
        ('remove all redundant files (keep source .do.txt and results: .pdf, .html, sphinx- dirs, .mwiki, .ipynb, etc.)', """doconce lightclean"""),
        ('remove all files that the doconce can regenerate', """doconce clean"""),
        ('change encoding', """doconce change_encoding utf-8 latin1 dofile"""),
        ('guess the encoding in a text', """doconce guess_encoding filename"""),
        ('find non-ascii characters in a file', """doconce find_nonascii_chars file1 file2 ..."""),
        ('split an html file into parts according to !split commands', """doconce split_html complete_file.html"""),
        ('create HTML slides from a (doconce) html file', """doconce slides_html slide_type complete_file.html"""),
        ('create LaTeX Beamer slides from a (doconce) latex/pdflatex file', """doconce slides_beamer complete_file.tex"""),
        ('create Remark slides from Markdown', """doconce slides_markdown complete_file.md remark --slide_style=light"""),
        ('replace bullets in lists by colored bullets', """doconce html_colorbullets file1.html file2.html ..."""),
        ('extract all exercises (projects and problems too)', """doconce extract_exercises tmp_mako__mydoc"""),
        ('grab selected text from a file', """doconce grab --from[-] from-text [--to[-] to-text] file > result"""),
        ('remove selected text from a file', """doconce remove --from[-] from-text [--to[-] to-text] file > result"""),
        ('list all figure, movie or included code files', """doconce grep FIGURE|MOVIE|CODE dofile"""),
        ('run spellcheck on a set of files', """doconce spellcheck [-d .mydict.txt] *.do.txt"""),
        ('   transform ptex2tex files (.p.tex) to ordinary latex file and manage the code environments', """doconce ptex2tex mydoc -DMINTED pycod=minted sys=Verbatim \\\n        dat=\\begin{quote}\\begin{verbatim};\end{verbatim}\end{quote}"""),
        ('make HTML file via pandoc from Markdown (.md) file', """doconce md2html file.md"""),
        ('make LaTeX file via pandoc from Markdown (.md) file', """doconce md2latex file.md"""),
        ('combine several images into one', """doconce combine_images image1 image2 ... output_file"""),
        ('report problems from a LaTeX .log file', """doconce latex_problems mydoc.log [overfull-hbox-limit]"""),
        ('list all figure files, movie files, and source code files needed', """doconce list_fig_src_files *.do.txt"""),
        ('list all labels in a document (for purposes of cleaning them up)', """doconce list_labels myfile"""),
        ('generate script for substituting generalized references', """doconce ref_external mydoc [pubfile]"""),
        ('check all links in HTML files', """doconce linkchecker *.html"""),
        ('change headings from "This is a Heading" to "This is a heading"', """doconce capitalize [-d .mydict.txt] *.do.txt"""),
        ('translate a latex document to doconce (requires usually manual fixing)', """doconce latex2doconce latexfile"""),
        ('check if there are problems with translating latex to doconce', """doconce latex_dislikes latexfile"""),
        ('translate an IPython/Jupyter notebook to doconce', """doconce ipynb2doconce notebookfile"""),
        ('typeset a doconce document with pygments (for pretty print of doconce itself)', """doconce pygmentize myfile [pygments-style]"""),
        ('generate a make.py script for translating a doconce file to various formats', """doconce makefile docname doconcefile [html sphinx pdflatex ...]"""),
        ('find differences between two files (diffprog can be difflib, diff, pdiff, latexdiff, kdiff3, diffuse, ...)', """doconce diff file1.do.txt file2.do.txt [diffprog]"""),
        ('find differences between the last two Git versions of several files', """doconce gitdiff file1 file2 file3 ..."""),
        ('convert csv file to doconce table format', """doconce csv2table somefile.csv"""),
        ('edit URLs to local files and place them in _static', """doconce sphinxfix_local_URLs file.rst"""),
        ('replace latex-1 (non-ascii) characters by html codes', """doconce latin2html file.html"""),
        ('fix common problems in bibtex files for publish import', """doconce fix_bibtex4publish file1.bib file2.bib ..."""),
        ('print the header (preamble) for latex file', """doconce latex_header"""),
        ('print the footer for latex files', """doconce latex_footer"""),
        ('expand short cut commands to full form in files', """doconce expand_commands file1 file2 ..."""),
        ('insert a table of exercises in a latex file myfile.p.tex', """doconce latex_exercise_toc myfile""")
    ]
    #doconce teamod name
    #doconce assemble name master.do.txt
    template = "\n\033[1m{0:70}\033[0m \033[94m{1:10}\033[0m"
    for help, command in _registered_commands:
        print(template.format(command, help))

def remove_options_from_command_line():
    """Remove options (--name) from sys.argv."""
    opts_index = [i for i in range(len(sys.argv))
                  if sys.argv[i].startswith('--')]
    for i in opts_index:
        del sys.argv[i]

def format():
    """
    Run the doconce module on a file (with extension .do.txt) in Doconce format
    and produce another format (latex, html, plain text, reStructuredText, ...)::

       doconce format html mydoc.do.txt
    """
    try:
        import doconce.doconce
    except ImportError:
        # use local doconce module in the doconce package source:
        try:
            thisdir = os.path.dirname(sys.argv[0])
            doconce_lib = os.path.join(thisdir, os.pardir, 'lib', 'doconce')
            sys.path.insert(0, doconce_lib)
            import doconce.doconce
            print('Successfull import of doconce locally')
        except ImportError as e:
            print(e)
            print('Could not import doconce from directory\n', os.getcwd())
            sys.exit(1)

    bg_session = doconce.doconce.format_driver()
    return bg_session

def main():
    from doconce import __version__ as version
    import doconce
    doconce_dir = os.path.dirname(doconce.__file__)
    if len(sys.argv) > 2 and sys.argv[1] == 'format' and misc_option('help'):
        help_format()
        sys.exit(0)
    elif len(sys.argv) == 1 or misc_option('help') and sys.argv[1] not in ['spellcheck', 'jupyterbook']:
        print('DocOnce version', version, '(from %s)' % doconce_dir)
        print('Usage: doconce command [optional arguments]')
        print('commands: %s' % (' '.join(commands)))
        help()
        sys.exit(0)
    if misc_option('version'):
        print('DocOnce version', version, '(from %s)' % doconce_dir)
        sys.exit(0)

    command = sys.argv[1]
    del sys.argv[1]
    # Execute the command
    if command not in commands:
        if command in ('html', 'latex', 'sphinx', 'rst', 'plain', 'gwiki', 'mwiki', 'epydoc', 'pandoc'):
            print('command', command, 'is not a legal command for doconce, did you mean')
            print('doconce format %s %s?' % (command, ' '.join(sys.argv[1:])))
        else:
            print('command "%s" is not legal, must be among\n' % command)
            print(', '.join(commands))
        sys.exit(0)
    retval = eval(command + '()')
    return retval

bg_session = main()
if bg_session is not None:
    print('...running bokeh bg_session.loop_until_closed() in the background')
    bg_session.loop_until_closed()
