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


"objects"


import getpass
import os
import sys
import termios
import time


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


from objx import Command, Default, Error, Event, Handler, Storage
from objx import cmnd, debug, forever, parse_command, scan


from objx import mods as modules


Cfg         = Default()
Cfg.mod     = "cmd,dbg,err,fnd,log,mod,mre,pwd,tdo,thr,ver"
Cfg.name    = "objx"
Cfg.version = "5"
Cfg.wd      = os.path.expanduser(f"~/.{Cfg.name}")
Cfg.pidfile = os.path.join(Cfg.wd, f"{Cfg.name}.pid")
Cfg.user    = getpass.getuser()


Error.output = print
Storage.wd   = os.path.expanduser("~/.objx")


class Console(Handler):

    def __init__(self):
        Handler.__init__(self)
        self.register("command", Command.handle)

    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)


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


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