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


"main"


import os
import readline
import sys
import termios
import time


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


from botl.client  import Client, cmnd, parse
from botl.disk    import Workdir, skel
from botl.handler import Event
from botl.log     import debug, enable
from botl.object  import Default
from botl.run     import broker, init, scan
from botl.thread  import errors, setout


from botl import modules


Cfg             = Default()
Cfg.dis         = ""
Cfg.mod         = "cmd,err,log,mod,tdo,thr,tmr"
Cfg.opts        = ""
Cfg.name        = __file__.rsplit(os.sep, maxsplit=1)[-1]
Cfg.version     = "120"
Cfg.wdr         = os.path.expanduser(f"~/.{Cfg.name}")
Cfg.pidfile     = os.path.join(Cfg.wdr, f"{Cfg.name}.pid")


Workdir.workdir = Cfg.wdr


class Console(Client):

    "Console"

    def __init__(self):
        Client.__init__(self)
        broker.add(self)

    def announce(self, txt):
        "disable announce."

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

    def poll(self):
        "poll console and create event."
        evt = Event()
        evt.orig = object.__repr__(self)
        evt.txt = input("> ")
        evt.type = "command"
        return evt

    def say(self, _channel, txt):
        "print to console"
        txt = txt.encode('utf-8', 'replace').decode()
        print(txt)


def wrap(func):
    "restore console."
    old2 = None
    try:
        old2 = termios.tcgetattr(sys.stdin.fileno())
    except termios.error:
        pass
    try:
        func()
    except (KeyboardInterrupt, EOFError):
        print("")
    finally:
        if old2:
            termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old2)


def main():
    "main"
    setout(print)
    parse(Cfg, " ".join(sys.argv[1:]))
    skel()
    Cfg.mod = ",".join(modules.__dir__())
    if "v" in Cfg.opts:
        enable(print)
        dte = " ".join(time.ctime(time.time()).replace("  ", " ").split()[1:])
        debug(f'{dte} {Cfg.name.upper()} {Cfg.opts.upper()} {Cfg.mod.upper()}')
    scan(modules, Cfg.mod, Cfg.sets.dis)
    if "c" in Cfg.opts:
        init(modules, Cfg.mod, Cfg.sets.dis)
        csl = Console()
        csl.start()
        while 1:
            time.sleep(1.0)
    elif Cfg.otxt:
        cmnd(Cfg.otxt, print)


if __name__ == "__main__":
    readline.redisplay()
    wrap(main)
    errors()
