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


"console"


import os
import readline
import sys
import termios
import time


from otpcr.command import command, parse
from otpcr.modules import face
from otpcr.object  import Default
from otpcr.runtime import Client, Event, errors, forever, init, later


MODS = None
NAME = Default.__module__.split(".", maxsplit=2)[-2]


if os.path.exists('mods'):
    from mods import face as MODS # pylint: disable=E0401


class Console(Client):

    "Console"

    def __init__(self):
        Client.__init__(self)
        self.register("command", command)

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

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

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


def banner():
    "show banner."
    tme = time.ctime(time.time()).replace("  ", " ")
    print(f"{NAME.upper()} since {tme}")


def wrap(func, outer):
    "reset console."
    old2 = None
    try:
        old2 = termios.tcgetattr(sys.stdin.fileno())
    except termios.error:
        pass
    try:
        func()
    except (KeyboardInterrupt, EOFError):
        outer("")
    except Exception as ex: # pylint: disable=W0718
        later(ex)
    finally:
        if old2:
            termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old2)


def main():
    "main"
    readline.redisplay()
    cfg = Default()
    parse(cfg, " ".join(sys.argv[1:]))
    if "v" in cfg.opts:
        banner()
    if "i" in cfg.opts:
        for mod, thr in init(face, MODS):
            if "v" in cfg.opts:
                mod.VERBOSE = print
            if "w" in cfg.opts:
                thr.join()
    csl = Console()
    csl.start()
    forever()


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