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


"feed rss into your channel"


import getpass
import os
import readline
import sys
import termios
import time


from rssbot import Client, Default, Error, Event, Storage
from rssbot import cmnd, debug, forever, modules, parse_command, scan


Cfg         = Default()
Cfg.mod     = "cmd,irc,mre,pwd,rss"
Cfg.name    = "rssbot"
Cfg.version = "508"
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   = 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)


def main():
    Storage.skel()
    parse_command(Cfg, " ".join(sys.argv[1:]))
    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:
        for mod in scan(modules, Cfg.mod, True):
            if "_thr" in dir(mod):
                mod._thr.join()
        csl.start()
        forever()
    if Cfg.otxt:
        scan(modules, Cfg.mod)
        return cmnd(Cfg.otxt)


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