#!/usr/bin/python3
# BOTLIB - bot
#
# this file is placed in the public domain

import atexit, os, pwd, readline, sys

from bot.hdl import Command, Handler, cmd
from bot.prs import parse_cli
from bot.thr import launch
from bot.trm import execute, termsave, termreset

# defines

wd = os.path.expanduser("~/.evrm")

# classes

class Console(Handler):

    "console class"

    def __init__(self):
        super().__init__()
        self.register("cmd", cmd)

    def announce(self, txt):
        "silence announcing"
        self.direct(txt)

    def direct(self, txt):
        print(txt)

    def input(self):
        "loop for input"
        while 1:
            try:
                e = self.poll()
            except EOFError:
                break
            self.put(e)
            e.wait()

    def poll(self):
        "wait for input"
        return Command(input("> "))

    def say(self, channel, txt):
        "strip channel from output"
        self.direct(txt)

    def start(self):
        "start console"
        super().start()
        launch(self.input)

# functions

def complete(text, state):
    "complete matches"
    matches = []
    if text:
        matches = [s for s in cmds if s and s.startswith(text)]
    else:
        matches = cmds[:]
    try:
        return matches[state]
    except IndexError:
        return None

def setcompleter(commands):
    "set the completer"
    cmds.extend(commands)
    readline.set_completer(complete)
    readline.parse_and_bind("tab: complete")
    atexit.register(lambda: readline.set_completer(None))

def daemon():
    pid = os.fork()
    if pid != 0:
        termreset()
        os._exit(0)
    os.setsid()
    os.umask(0)
    si = open("/dev/null", 'r')
    so = open("/dev/null", 'a+')
    se = open("/dev/null", 'a+')
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())

def main():
    import bot.obj
    cfg = parse_cli(wd)
    if "d" in cfg.opts:
        daemon()
        h = Handler()
    else:
        h = Console()
    h.walk("evrm")
    if cfg.txt:
        return h.cmd(cfg.otxt)
    h.init(cfg.sets.mods)
    h.start()
    h.wait()

# runtime

cmds = []
     
execute(main)
os._exit(0)
