#!/usr/bin/env python3
# This file is placed in the Public Domain.
#
# pylint: disable=C0103,C0115,C0116,C0209,C0413,W0201,R0903,W0212,W0105,W0613


"program"


import os
import sys
import termios
import time


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


from bot import CLI, Commands, Default, Errors, Event, Storage
from bot import command, forever, parse,  lsmod, modules, scan


Cfg = Default()
Cfg.name = __file__.rsplit(os.sep, maxsplit=1)[-1].lower()
Storage.wd = os.path.expanduser(f"~/.{Cfg.name}")


class CLI(CLI):

    def dosay(self, channel, txt):
        print(txt.encode('utf-8', 'replace').decode())
        sys.stdout.flush()


class Console(CLI):


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


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


def main():
    parse(Cfg, " ".join(sys.argv[1:]))
    if "v" in Cfg.opts:
        dte = time.ctime(time.time()).replace("  ", " ")
        print(f"{Cfg.name.upper()} started {Cfg.opts.upper()} started {dte}")
    Cfg.mod = ",".join((lsmod(modules.__path__[0])))
    if 'c' in Cfg.opts:
        scan(modules, Cfg.mod, True)
        csl = Console()
        csl.start()
        forever()
    scan(modules, Cfg.mod)
    cli = CLI()
    command(Cfg.otxt, cli)
    Errors.show()


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