#!/usr/bin/env python3
# This file is placed in the Public Domain.
# pylint: disable=C0413,W0611


"prompt"


import getpass
import os
import readline
import sys
import termios


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


from objr import Client
from objt import errors
from objx import Default, fmt
from objz import Broker, Commands, Config
from objz import command, forever, modnames, parse, wrap


from objbot.modules import face


Cfg = Config("objbot")
Cfg.mod = ",".join(modnames(face))


class Event(Default):

    "Event"

    def __init__(self):
        Default.__init__(self)
        self.orig    = ""
        self.result  = []
        self.txt     = ""

    def reply(self, txt):
        "add text to the result"
        self.result.append(txt)


class CLI(Client):

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

    def raw(self, txt):
        print(txt)
        sys.stdout.flush()


def srv(event):
    "create service file (pipx)."
    if event.args:
        name = event.args[0]
    else:
        name  = getpass.getuser()
    event.reply(TXT % (Cfg.name.upper(), name, name, name))


def main():
    "main"
    Commands.add(srv)
    parse(Cfg, " ".join(sys.argv[1:]))
    clt = CLI()
    if Cfg.txt:
        evt = Event()
        evt.txt = Cfg.otxt
        parse(evt)
        command(clt, evt)


TXT = """[Unit]
Description=%s
After=network-online.target

[Service]
Type=simple
User=%s
Group=%s
ExecStart=/home/%s/.local/bin/objbots

[Install]
WantedBy=multi-user.target"""


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