#!/usr/bin/env python3
# This file is placed in the Public Domain.
#
# pylint: disable=C,R,W0201,W0212,W0105,W0613,W0406,E0102,W0611,W0718,W0125


"runtime"


import getpass
import os
import sys
import termios
import time


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


from obj import Default, Object
from prg import Client, Error, Event, Storage
from prg import cmnd, debug, forever, parse_command, scan, spl
from bot import modules


Cfg         = Default()
Cfg.mod     = "cmd,err,irc,mod,mre,pwd,rss,thr"
Cfg.name    = "bot"
Cfg.version = "70"
Cfg.wd      = os.path.expanduser(f"~/.{Cfg.name}")
Cfg.pidfile = os.path.join(Cfg.wd, f"{Cfg.name}.pid")
Cfg.user    = getpass.getuser()


Storage.wd   = Cfg.wd


class Console(Client):

    def announce(self, txt):
        if "v" in Cfg.opts:
            self.say("", txt)

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

    def say(self, channel, txt):
        txt = txt.encode('utf-8', 'replace').decode()
        print(txt)


def wrap(func) -> None:
    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)


"runtime"


if os.path.exists("mods"):
    import mods
else:
    mods = None


def main():
    Storage.skel()
    parse_command(Cfg, " ".join(sys.argv[1:]))
    if "a" in Cfg.opts:
        Cfg.mod = ",".join(modules.__dir__())
        if "m" in Cfg.opts:
            Cfg.mod += "," +  ",".join(mods.__dir__())
    if "v" in Cfg.opts:
        dte = time.ctime(time.time()).replace("  ", " ")
        debug(f"{Cfg.name.upper()} started {Cfg.opts.upper()} started {dte}")
    csl = Console()
    if "c" in Cfg.opts:
        scan(modules, Cfg.mod, True, True)
        if "m" in Cfg.opts:
            scan(mods, Cfg.mod, True, True)
        csl.start()
        forever()
    if Cfg.otxt:
        scan(modules, Cfg.mod)
        if "m" in Cfg.opts:
            scan(mods, Cfg.mod)
        return cmnd(Cfg.otxt)


if __name__ == "__main__":
    wrap(main)
    Error.show()
