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


"console"


import getpass
import os
import readline
import sys
import termios
import time


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


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


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


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."
    old3 = None
    try:
        old3 = termios.tcgetattr(sys.stdin.fileno())
    except termios.error:
        pass
    try:
        func()
    except (KeyboardInterrupt, EOFError):
        outer("")
    except Exception as ex:
        later(ex)
    finally:
        if old3:
            termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old3)


def main():
    "main"
    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)
