#!/usr/bin/env python
#coding=utf8

'''
CloudControl CLI Parser
'''

import sys
import os, os.path

class Parser(object):
    def __init__(self, options, alias):
        self.interactive = sys.stderr.isatty() and sys.stdin.isatty()
        # if os.environ.has_key("ITPASS_HISTFILE"):
        #     self.histfile = os.environ["ITPASS_HISTFILE"]
        # else:
        #     self.histfile = "%s/.history"%os.environ["ITPASS_ROOT"]
        # if os.environ.has_key("ITPASS_HISTSIZE"):
        #     self.histsize = int(os.environ["ITPASS_HISTSIZE"])
        # else:
        #     self.histsize = 500
        # if self.interactive:
        #     try:
        #         readline.read_history_file(self.histfile)
        #     except IOError:
        #         pass
        #     readline.set_history_length(self.histsize)
        #     readline.parse_and_bind("tab: complete")
        #     readline.set_completer_delims(string.whitespace)
        #     readline.set_completer(Completer().syntax_completion)

    def _prompt(self):
        '''Show a parser prompt'''
        return "> "
        bang = "#" if Keyring().has_unlocked_key() else "$"
        try:
            cwd = re.sub(self.rootpath, '~', os.getcwd())
        except:
            cwd = "?"
        return "%s:%s %s "%(os.path.basename(sys.argv[0]), cwd, bang)

    def _interactive_parser(self):
        '''Interactive shell parser'''
        while True:
            try:
                line = raw_input(self._prompt())
                Keyring().check_timeout()
                ret = self._parser(line)
                if ret != 0:
                    warn("function return %s, not 0"%ret)
            except EOFError:
                out("")
                break
            except SystemExit:
                break
            except KeyboardInterrupt:
                out("")
            except myError, e:
                error(str(e))
            except Exception, e:
                error(e)
                if os.environ.has_key("ITPASS_DEBUG"):
                    raise
                else:
                    warn("this is a not expected error, please report it")
        try:
            readline.write_history_file(self.histfile)
        except IOError:
            pass
        out("Tcho!")

    def _parser(self, string):
        '''Parse a string'''
        cmd_list = [ x.strip() for x in Parser.split(string, ";|\n", show_quote=True) ]
        ret = 0
        for cmd in cmd_list:
            if (cmd == "" or cmd[0] == "#"):
                continue
            elif (cmd[0] == "!"):
                p = subprocess.Popen(cmd[1:], close_fds=True, shell=True)
                p.wait()
                ret = p.returncode
            elif (cmd[0] == "?"):
                Command("help").call()
                ret = 0
            else:
                Command(cmd).call()
                ret = 0
        return ret

    def parse(self, command = ""):
        '''Parser start'''
        if command == "":
            if self.interactive:
                return self._interactive_parser()
            else:
                fatal("Not a TTY. Unable to start interactive parser")
        else:
            self._parser(command)