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


"console"


import os
import readline
import sys
import termios
import time


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


from opd.object   import Config, parse
from opd.persist  import NAME, Workdir
from opd.__main__ import command, scan
from opd.modules  import face
from opd.runtime  import Client, Errors, Event, errors, forever, later


"defines"


cfg  = Config()


"classes"


class Console(Client):

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

    def callback(self, evt):
        Client.callback(self, evt)
        evt.wait()

    def poll(self):
        evt = Event()
        evt.txt = input("> ")
        evt.type = "command"
        return evt

    def raw(self, txt):
        print(txt)


"utilities"


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


def wrap(func):
    old = None
    try:
        old = termios.tcgetattr(sys.stdin.fileno())
    except termios.error:
        pass
    try:
        func()
    except (KeyboardInterrupt, EOFError):
        print("")
    except Exception as ex:
        later(ex)
    finally:
        if old:
            termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old)
    for txt in errors():
        print(txt)


"runtime"


def main():
    parse(cfg, " ".join(sys.argv[1:]))
    if "v" in cfg.opts:
        banner()
    for mod, thr in scan(face, init="i" in cfg.opts, disable=cfg.sets.dis):
        if "v" in cfg.opts and "output" in dir(mod):
            mod.output = print
        if thr and "w" in cfg.opts:
            thr.join()
    if "c" in cfg.opts:
        csl = Console()
        csl.start()
        forever()
    elif cfg.txt:
        evt = Event()
        evt.txt = cfg.txt
        evt.type = "command"
        csl = Console()
        command(csl, evt)
        evt.wait()


def wrapped():
    wrap(main)
    

if __name__ == "__main__":
    wrapped()
