#!/usr/bin/env python
#

"""
gjs: execute arbitrary Javascript in graphterm
"""

from __future__ import absolute_import, print_function

import sys

from optparse import OptionParser

try:
    import gterm
except ImportError:
    import graphterm.bin.gterm as gterm

usage = "usage: %prog [-f file] [-e js_string] [js_func arg1 ...]"
parser = OptionParser(usage=usage)
parser.add_option("-f", "--file",
                  action="store_true", dest="file", default=False,
                  help="Read from file")
parser.add_option("-v", "--verbose",
                  action="store_true", dest="verbose", default=False,
                  help="Verbose output")
parser.add_option("-e", "--eval", dest="eval", default="",
                  help="Evaluate string")

(options, args) = parser.parse_args()

if options.file:
    if not args:
        print("Please provide filename", file=sys.stderr)
        sys.exit(1)
    with open(args[0], "r") as f:
        js = "".join(f.readlines())
elif options.eval:
    js = options.eval
elif args:
    if "=" in args[0] or (len(args) >= 2 and args[1].startswith("=")):
        js = " ".join(args)
    else:
        js = args[0] + "(" + ", ".join(arg if arg.isdigit() else '"'+arg+'"' for arg in args[1:]) + ")"
else:
    print(parser.get_usage(), file=sys.stderr)
    sys.exit(1)
    
if options.verbose:
    print(js)

Headers = {"content_type": "text/plain"}
Headers["x_gterm_response"] = "eval_js"
Headers["x_gterm_parameters"] = {"echo": "terminal"}

gterm.wrap_write(js, headers=Headers, stderr=True)

try:
    lines = sys.stdin.readlines()
    if not sys.stdout.isatty():
        print("".join(lines))
except KeyboardInterrupt:
    pass

    
