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


"console"


import os
import readline
import sys
import termios


from obx.command import Event, command, parse
from obx.default import Config
from obx.modules import face
from obx.runtime import Client, Logging
from obx.runtime import banner, errors, forever, init, later


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


cfg = Config()


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 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:
        later(ex)
    finally:
        if old2:
            termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old2)


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


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