#!/usr/bin/env python3
# XMPP bot
import argparse
import slixmpp
import configparser

CONFIG_PATH = "./config.ini"

VERSION='0.1.0'

def processmsg(msg, rcpt):
	if !msg.startswith("!"):
		return ""
	if msg.startswith("http"):
		return "link"
	elif "youtube" in msg:
		return msg.replace("youtube.com", "iv.datura.network")

def show_version():
    print("chatbot " + VERSION)
    print("License AGPLv3+: GNU AGPL version 3 or later <https://gnu.org/licenses/gpl.html>")
    print("This is free software: you are free to change and redistribute it.")
    print("There is NO WARRANTY, to the extent permitted by law.")


class MUCBot(slixmpp.ClientXMPP):

    def __init__(self, jid, password, nick, room):
        slixmpp.ClientXMPP.__init__(self, jid, password)

        self.nick = nick
        self.room = room
        self.add_event_handler("session_start", self.start)
        self.add_event_handler("groupchat_message", self.muc_message)

    async def start(self, event):
        await self.get_roster()
        self.send_presence()
        self.plugin['xep_0045'].join_muc(self.room,self.nick)

    def muc_message(self, msg):
        rcpt=msg['from'].bare
        processmsg(msg['body'], rcpt)
        if msg['type'] in ('chat', 'normal'):
            self.send_message(mto=rcpt,mbody="%s: %s" % (msg['mucnick'],msg['body']),mtype='groupchat')


if __name__ == '__main__':
    argparser = argparse.ArgumentParser(description="XMPP bot")
    argparser.add_argument("--version", dest="version", help="print version information and exit", action="store_true")
    args=argparser.parse_args()

    ## Version argument
    if args.version:
        show_version()
        exit()

    config = configparser.ConfigParser()
    config.read(CONFIG_PATH)
    JID = config.get('credentials', 'JID')
    PASSWORD = config.get('credentials', 'PASSWORD')
    NICK = config.get('credentials', 'NICK')
    ROOM1 = config.get('credentials', 'ROOM')
    HOST = None
    PORT = 5222
    if "host" in config.options('credentials'):
        HOST = config.get('credentials', 'HOST')
    if "port" in config.options('credentials'):
        PORT = config.get('credentials', 'PORT')


    xmpp = MUCBot(JID, PASSWORD, NICK, ROOM)
    xmpp.register_plugin('xep_0030') # Service Discovery
    xmpp.register_plugin('xep_0045') # Multi-User Chat
    xmpp.register_plugin('xep_0199') # XMPP Ping

    # Connect to the XMPP server and start processing XMPP stanzas.
    if HOST != None:
        xmpp.connect(address=(HOST,int(PORT)))
    else:
        xmpp.connect()
    xmpp.process()

