#!/usr/bin/env python 
"""A simplistic client for tarantool/box: administrative
console and SQL client.

On startup, establishes a connection to tarantool server.
Then, reads commands from stdin, and sends them to stdout.
"""
__author__ = "Konstantin Osipov <kostja.osipov@gmail.com>"

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

import argparse
import socket
import sys
import string
from lib.admin_connection import AdminConnection, is_admin_re
from lib.box_connection import BoxConnection

class Options:
  def __init__(self):
    """Add all program options, with their defaults."""

    parser = argparse.ArgumentParser(
        description = "Tarantool administrative console client.")

    parser.add_argument(
        "--host",
        dest = 'host',
        metavar = "host",
        default = "localhost",
        help = "Host to connect to. Default: localhost")


    parser.add_argument(
        "--port",
        dest = "port",
        default = 33013,
        help = "Server port to connect to. Default: 33013")

    parser.add_argument(
        "--admin-port",
        dest = "admin_port",
        default = 33015,
        help = "Server administrative port to connect to. Default: 33015")

    parser.add_argument(
        "--prompt",
        metavar = "prompt",
        dest = "prompt",
        default = "tarantool> ",
        help = """Command prompt. Set to "" for no prompt. Default:
        tarantool> """)
    
    self.args = parser.parse_args()

def init_readline_history():
  import os, readline, atexit
  histfile = os.path.join(os.environ["HOME"], ".tarantool_client_history")
  try:
    readline.read_history_file(histfile)
  except IOError:
    pass
  atexit.register(readline.write_history_file, histfile)
  del os, histfile


def do_command(admin_con, data_con, line):
  output = None 
  if is_admin_re.match(line):
    output = admin_con.execute(line + "\n")
  else:
    output = data_con.execute(line)
  return output 

def main():
  init_readline_history()
  options = Options()
  admin_con = AdminConnection(options.args.host, options.args.admin_port)
  data_con = BoxConnection(options.args.host, options.args.port)
  try:
    admin_con.connect()
    data_con.connect()
    while True:
      sys.stdout.flush()
      line = raw_input(options.args.prompt)
      if not line or line == "exit":
        raise EOFError()
      output = do_command(admin_con, data_con, line)
      sys.stdout.write(output)
  except KeyboardInterrupt:
    print "\nAborted"
  except EOFError:
    print "Bye"
  except (RuntimeError, socket.error) as e:
    print "Fatal error: ", repr(e)
    return -1
  finally:
    admin_con.disconnect()
    data_con.disconnect()

  return 0

if __name__ == "__main__":
  exit(main())

