#!python
# This file is placed in the Public Domain.
#
# pylint: disable=C,I,R


"skull, bones and number"


__author__ = "Bart Thate <programmingobject@gmail.com>"


import os
import readline
import sys
import termios
import _thread


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


from sbn import Broker, Cfg, Command, Event, Logging, Persist, Reactor
from sbn import banner, parse, scan, waiter
from sbn import modules


Cfg.mod = "bsc"
Cfg.name = "sbn"
Cfg.verbose = False
Cfg.version = 20


Persist.workdir = os.path.expanduser("~/.{Cfg.name}")


readline.redisplay()


class CLI(Reactor):

    def __init__(self):
        Reactor.__init__(self)
        Broker.add(self)
        self.register("event", Command.handle)

    def announce(self, txt):
        self.raw(txt)

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


class Console(CLI):

    def __init__(self):
        CLI.__init__(self)

    def handle(self, evt):
        Command.handle(evt)
        evt.wait()

    def poll(self):
        try:
            return self.event(input("> "))
        except EOFError:
            _thread.interrupt_main()

def cprint(txt):
    print(txt)
    sys.stdout.flush()


def wrap(func) -> None:
    old = termios.tcgetattr(sys.stdin.fileno())
    try:
        func()
    except (EOFError, KeyboardInterrupt):
        print("")
        sys.stdout.flush()
    finally:
        termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old)
        waiter()


def main():
    parse(Cfg, " ".join(sys.argv[1:]))
    if "v" in Cfg.opts:
        Logging.raw = print
        Logging.verbose = True
    if "c" in Cfg.opts:
        print(banner(Cfg.name, Cfg.version))
        csl = Console()
        scan(modules, Cfg.mod, True, "a" in Cfg.opts)
        csl.loop()
    else:
        cli = CLI()
        scan(modules, Cfg.mod, False, True)
        evt = Event()
        evt.orig = repr(cli)
        evt.txt = Cfg.txt
        Command.handle(evt)


if __name__ == "__main__":
    wrap(main)
    waiter()
