#!/usr/bin/env python2
# -*- mode: python -*-
'''Quick and dirty script for executing reql from the commandline'''

import argparse
import reqlcli
import os.path
from pygments.styles import STYLE_MAP

import rethinkdb as r

DESC = '''\
Run ReQL commands in the terminal.

If the output is being piped, will print one document per line and not
use color
'''


def main(argv):
    parser = argparse.ArgumentParser(description=DESC)
    parser.add_argument('--port', '-p', type=int, default=28015,
                        help='RethinkDB driver port')
    parser.add_argument('--host', '-t', default='localhost',
                        help='RethinkDB host address')
    parser.add_argument('--auth_key', '-k', default='',
                        help='RethinkDB auth key')
    parser.add_argument('--db', '-d', default='test',
                        help='default database for queries')
    parser.add_argument('--pagesize', '-g', type=int, default=10,
                        help='Documents per page. No effect on piped output')
    parser.add_argument('--style', '-s', default='monokai',
                        help='Source code color scheme. Valid values: '
                        + ', '.join(STYLE_MAP.keys()))
    parser.add_argument('--array', '-a', dest='format', action='store_const',
                        const='array', default='auto',
                        help='Force JSON array output')
    parser.add_argument('--newline', '-n', dest='format', action='store_const',
                        const='newline', default='auto',
                        help='Force one document per line output')
    parser.add_argument('--color', '-c', dest='format', action='store_const',
                        const='color', default='auto',
                        help='Force color/pretty printed output')
    parser.add_argument('--auto', dest='format', action='store_const',
                        const='auto', default='auto',
                        help='Decide output format based on whether output '
                        'is being piped (this is the default)')
    parser.add_argument('querystring', metavar='QUERY', help='ReQL query to run')
    parser.add_argument('files', metavar='FILE', nargs='*',
                        help='Input files. Contents will be available to '
                        'the queries as legal variable names from the filenames'
                        '  (e.g. "file+name.tar.gz" becomes "file_name")')

    args = parser.parse_args(argv[1:])

    files = {
        reqlcli.filename_to_var(filename): open(filename, 'rb').read()
        for filename in args.files
    }
    conn = r.connect(args.host, args.port, args.db, args.auth_key)
    output = reqlcli.Output.make(args.format, args.style, args.pagesize)

    ex = reqlcli.ReQLExecution(args.querystring, files, conn, output)()

if __name__ == '__main__':
    import sys
    main(sys.argv)
