#!/usr/bin/env python3
# This file is placed in the Public Domain.


import inspect
import json
import logging
import os
import sys
import threading
import time
import _thread


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


from tob.clients import Client
from tob.command import Commands, Config, command, modules, scan, scanner
from tob.handler import Event
from tob.logging import level
from tob.methods import parse
from tob.persist import Workdir, moddir, pidname, skel
from tob.runtime import NAME, check, daemon, forever, inits, pidfile
from tob.runtime import excepthook, privileges, wrap, wrapped
from tob.threads import launch
from tob.utility import md5sum, spl


#import tobot.modules as MODS
import examples as MODS


TXT = " ".join(sys.argv[1:])


Config.name = "tob"
Config.version = 137


sys.excepthook = threading.excepthook = excepthook


class CLI(Client):

    def __init__(self):
        Client.__init__(self)
        self.register("command", command)

    def raw(self, txt):
        print(txt.encode('utf-8', 'replace').decode("utf-8"))


class Console(CLI):

    def callback(self, event):
        if not event.txt:
            return
        super().callback(event)
        event.wait()

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


def cmd(event):
    event.reply(",".join(sorted(Commands.names or Commands.cmds)))


def banner(name, version):
    tme = time.ctime(time.time()).replace("  ", " ")
    logger = logging.getLogger()
    print("%s %s since %s (%s)" % (
                                   name.upper(),
                                   version,
                                   tme,
                                   logging.getLevelName(logger.getEffectiveLevel())
                                  ))
    sys.stdout.flush()


def background():
    daemon(check("v"))
    privileges()
    Commands.add(cmd)
    pidfile(pidname(NAME))
    inits(MODS, Config.sets.init or "irc,rss")
    forever()


def console():
    import readline # noqa: F401
    parse(Config, TXT)
    level(Config.sets.level or "warn")    
    if "v" in Config.opts:
        banner(Config.name, Config.version)
    mods = []
    if "a" in Config.opts:
        mods = modules(MODS)
    scanner(MODS, mods)
    Commands.add(cmd)
    csl = Console()
    for _mod, thr in inits(MODS, Config.sets.init or mods):
        thr.join(30.0)
    csl.start()
    forever()


def control():
    if len(sys.argv) == 1:
        return
    scanner(MODS)
    Commands.add(cmd)
    csl = CLI()
    evt = Event()
    evt.orig = repr(csl)
    evt.txt = " ".join(sys.argv[1:])
    evt.type = "command"
    command(evt)
    evt.wait()


def service():
    privileges()
    banner(Confg.name, Config.version)
    scanner(MODS)
    Commands.add(cmd)
    pidfile(pidname(NAME))
    inits(MODS, Config.sets.init or "irc.rss")
    forever()


def main():
    if check("c"):
        wrap(console)
    elif check("d"):
        background()
    elif check("s"):
        wrapped(service)
    else:
        wrapped(control)


if __name__ == "__main__":
    main()
