#!/usr/bin/env python3
# This file is placed in the Public Domain.
# pylint: disable=C0413,W0611


"prompt"


import os
import readline
import sys
import termios
import time


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


from otpcr.errors  import errors
from otpcr.main    import Broker, Client, Config, Event, command, debug
from otpcr.main    import enable, forever, initer, modnames, parse, spl
from otpcr.modules import face
from otpcr.object  import Default
from otpcr.runtime import launch


Cfg = Config()
Cfg.mod = "cmd,dbg,err,mod,srv,thr"


rpr = object.__repr__


class Console(Client):

    "Console"

    def callback(self, evt):
        Client.callback(self, evt)
        evt._thr.join()

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

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


def banner():
    "show banner."
    tme = time.ctime(time.time()).replace("  ", " ")
    debug(f"{Cfg.name.upper()} since {tme}")


def wrap(func):
    "reset console."
    old3 = None
    try:
        old3 = termios.tcgetattr(sys.stdin.fileno())
    except termios.error:
        pass
    try:
        func()
    except (KeyboardInterrupt, EOFError):
        print("")
    finally:
        if old3:
            termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old3)
    errors(print)


def main():
    "main"
    parse(Cfg, " ".join(sys.argv[1:]))
    if "v" in Cfg.opts:
        enable(print)
        banner()
    if "i" in Cfg.opts:
        Cfg.mod = ",".join(modnames(face))
        for thr in initer(Cfg.mod, face):
            thr.join()
    csl = Console()
    csl.start()
    forever()


def wraps():
    "Wrap main."
    wrap(main)


if __name__ == "__main__":
    wraps()
    