#!/usr/bin/env python3
# This file is placed in the Public Domain.


"console"


import getpass
import os
import readline
import sys


sys.path.insert(0, os.getcwd())



from otpcr.config  import Config
from otpcr.client  import Client
from otpcr.command import Event, command, parse, scanner
from otpcr.main    import banner, forever, initter, modnames
from otpcr.main    import privileges, wrap
from otpcr.modules import face
from otpcr.runtime import errors


if os.path.exists('mods'):
    from mods import face as MODS
else:
    MODS = None


class Console(Client):

    "Console"

    def callback(self, evt):
        "wait for result."
        Client.callback(self, evt)
        if evt._thr:
            evt._thr.join()

    def poll(self):
        "poll console and create event."
        evt = Event()
        evt.orig = repr(self)
        evt.txt = input("> ")
        evt.type = "command"
        return evt

    def raw(self, txt):
        "print text."
        print(txt)


def main():
    "main"
    readline.redisplay()
    parse(Config, " ".join(sys.argv[1:]))
    modstr = ",".join(modnames(face, MODS))
    user = getpass.getuser()
    if "v" in Config.opts:
        banner(print)
    for mod in scanner(modstr, face, MODS):
        if "v" in Config.opts:
            mod.VERBOSE = print
    if "i" in Config.opts:
        thrs = initter(modstr, face, MODS)
        for thr in thrs:
            thr.join()
    csl = Console()
    csl.start()
    forever()


if __name__ == "__main__":
    wrap(main, print)
    errors(print)
