# -*- coding: utf-8 -*-
""" A simple script to see who a (host)mask will effect
Author: Øyvind 'Mr.Elendig' Heggstad
Usage: /tmask foo!bar@baz  * and ? should work as expected"""

import weechat
import re

SNAME = 'tmask'
SVERSION = '0.1'

weechat.register(SNAME, SVERSION, '', 'Shows who a mask matches')
weechat.add_command_handler("tmask", "test")


def test(server, args): # weechat passes the current server as the first arg
    """Applies the mask to the nicks in the current channel, prints the result to the current buffer"""
    if not args:
        weechat.prnt('Error: No mask specified.')
        return weechat.PLUGIN_RC_OK
    elif len(args.split()) > 1:
        weechat.prnt('Error: Sorry, only one mask at a time.')
        return weechat.PLUGIN_RC_OK
    elif not re.match(r'\S*!\S*@\S', args):
        weechat.prnt('Error: Not a valid mask.')
        return weechat.PLUGIN_RC_OK

    mask = args.replace('?', '.?')
    mask = mask.replace('*', '.*')
    mask = re.compile(mask, re.I)

    channel = weechat.get_info('channel', server)
    nicks = weechat.get_nick_info(server, channel)

    result = []
    for nick in nicks:
        n = '%s!%s' % (nick, nicks[nick]['host'])
        if mask.match(n):
            result.append('%s (%s)' % (nick, n))
    
    if result:
        weechat.prnt('Matches for: %s' % args)
        for i in result:
            weechat.prnt(i)
    else:
        weechat.prnt('No match for: %s' % args)

    return weechat.PLUGIN_RC_OK
