#!/usr/bin/env python
# -*- coding: utf-8 -*-
USAGE = """omt-py

A fairly generic tool that allows you to capture all of the output from
a terminal application (including shells). This output is then rendered in
a pure-python terminal emulator (pyte), and the resulting virtual "screen"
is dumped to either generic JSON or a generic HTML snippet that can then
be used to by other tools or inserted into a webpage.

There are issues with some complex curses applications that use certain
CSI control codes not (yet) supported by pyte. For example, htop will not
work.

This tool was designed specifically to turn zsh themes into a gallery.


Example:

    echo "ls\\nexit\\n" > omt-py html -- /bin/zsh


Commands:
    omt-py json             - Generates a JSON representation of the screen.
    omt-py html             - Generates a generic HTML snippet or a standalone
                              page.
    omt-py iterm-to-css     - Converts an iTerm2 theme into CSS suitable for
                              usage with the HTML snippets generated by omt.

Usage:
    omt-py json [options] -- <argv>...
    omt-py html [options] -- <argv>...
    omt-py iterm-to-css [--prefix=<prefix>] <source>

Options:
    --width=<columns>       The number of columns for the pseudo-terminal.
                            [default: 80]
    --height=<lines>        The number of lines for the pseudo-terminal.
                            [default: 24]
    --standalone            When generating HTML, generate a standalone page
                            instead of a generic snippet.
    --theme=<source>        When generating standalone HTML, use this iTerm2
                            theme for the CSS.
    --prefix=<prefix>       The prefix to use for CSS selectors.
                            [default: omt]
"""
import sys
import json
import docopt

from jinja2 import Environment, PackageLoader

from omt.core import process_to_screen
from omt.util import iterm_to_css


def from_cli():
    args = docopt.docopt(USAGE)

    if args['json']:
        screen = process_to_screen(
            args['<argv>'],
            stdin=sys.stdin,
            width=int(args['--width']),
            height=int(args['--height'])
        )

        sys.stdout.write(json.dumps(screen))
        sys.stdout.write('\n')
        sys.stdout.flush()
    elif args['html']:
        screen = process_to_screen(
            args['<argv>'],
            stdin=sys.stdin,
            width=int(args['--width']),
            height=int(args['--height'])
        )

        env = Environment(loader=PackageLoader('omt', 'templates'))
        if not args['--standalone']:
            # We're just making a generic snippet which can be inserted
            # into other pages.
            template = env.get_template('screen.jinja')
            sys.stdout.write(template.render(screen=screen))
        else:
            # We're making a standalone page, so we need an iTerm2 theme
            # for the CSS.
            with open(args['--theme'], 'rb') as fin:
                style = iterm_to_css(fin.read())

            template = env.get_template('standalone.jinja')
            sys.stdout.write(template.render(screen=screen, style=style))

        sys.stdout.write('\n')
        sys.stdout.flush()
    elif args['iterm-to-css']:
        with open(args['<source>'], 'rb') as fin:
            sys.stdout.write('\n'.join(
                iterm_to_css(
                    fin.read(),
                    prefix=args['--prefix']
                )
            ))
        sys.stdout.flush()

    return 0


if __name__ == '__main__':
    sys.exit(from_cli())
