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


"main"


import readline
import sys
import termios
import time


from rssbot import Censor, Cfg, CLI, Commands, Errors, Message
from rssbot import command, debug, forever, init, isop, modules, parse


class CLI(CLI):

    def say(self, channel, txt):
        txt = txt.encode('utf-8', 'replace').decode()
        sys.stdout.write(txt)
        sys.stdout.write("\n")
        sys.stdout.flush()


class Console(CLI):

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


def main():
    parse(Cfg, " ".join(sys.argv[1:]))
    if isop("v"):
        Censor.output = print
        dte = time.ctime(time.time()).replace("  ", " ")
        debug(f"{Cfg.name.upper()} started {Cfg.opts.upper()} started {dte}")
    if isop("c"):
        init(modules, Cfg.mod, isop("w"))
        csl = Console()
        if isop("t"):
            csl.threaded = True
        csl.start()
        wait = True
        forever()
        return
    cli = CLI()
    command(Cfg.otxt, cli)


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


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