// Bot
//
// Douglas Thrift
//
// Bot.java

/*  Copyright 2011 Douglas Thrift
 *
 *  This file is part of Big Screen Bot.
 *
 *  Big Screen Bot is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Big Screen Bot is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Big Screen Bot.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.douglasthrift.bigscreenbot;

import java.net.InetAddress;
import java.net.UnknownHostException;

import java.util.Collection;

import java.util.regex.Pattern;

import org.apache.oro.text.GlobCompiler;

import org.jibble.pircbot.PircBot;
import org.jibble.pircbot.User;

public abstract class Bot extends PircBot
{
    protected boolean isNickInChannels(String nick)
    {
        for (String channel : getChannels())
            for (User user : getUsers(channel))
                if (user.equals(nick))
                    return true;

        return false;
    }

    protected static Pattern compileNickMask(String mask)
    {
        return Pattern.compile(GlobCompiler.globToPerl5(mask.toCharArray(), GlobCompiler.DEFAULT_MASK), Pattern.CASE_INSENSITIVE);
    }

    protected static boolean matchNickMasks(String sender, String login, String hostname, Collection<Pattern> masks)
    {
        String nick = sender + "!" + login + "@" + hostname;

        for (Pattern mask : masks)
            if (mask.matcher(nick).matches())
                return true;

        try
        {
            InetAddress address = InetAddress.getByName(hostname);
            String name = address.getCanonicalHostName();

            if (!name.equalsIgnoreCase(hostname))
            {
                nick = sender + "!" + login + "@" + name;

                for (Pattern mask : masks)
                    if (mask.matcher(nick).matches())
                        return true;
            }
        }
        catch (UnknownHostException exception) {}

        return false;
    }
}

// vim: expandtab
