/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pw.yumc.Residence.chat;

import java.util.ArrayList;
import java.util.List;

import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;

import com.bekvon.bukkit.residence.event.ResidenceChatEvent;

import pw.yumc.Residence.ResidenceMain;

/**
 *
 * @author Administrator
 */
public class ChatChannel {

    protected List<String> members;
    protected final String name;
    protected final ResidenceMain plugin;
    protected final PluginManager pm;

    public ChatChannel(final ResidenceMain plugin, final String channelName) {
        this.plugin = plugin;
        pm = plugin.getServer().getPluginManager();
        name = channelName;
        members = new ArrayList<String>();
    }

    public void chat(final String sourcePlayer, final String message) {
        final Server serv = plugin.getServer();
        final ChatColor color = plugin.getConfigManager().getChatColor();
        final ResidenceChatEvent cevent = new ResidenceChatEvent(plugin.getResidenceManager().getByName(name), serv.getPlayer(sourcePlayer), message, color);
        pm.callEvent(cevent);
        if (cevent.isCancelled()) {
            return;
        }
        for (final String member : members) {
            final Player player = serv.getPlayer(member);
            if (player != null) {
                player.sendMessage(cevent.getColor() + sourcePlayer + ": " + cevent.getChatMessage());
            }
        }
        plugin.getLogger().info("ResidentialChat[" + name + "] - " + sourcePlayer + ": " + cevent.getChatMessage());
    }

    public boolean hasMember(final String player) {
        return members.contains(player);
    }

    public void join(final String player) {
        if (!members.contains(player)) {
            members.add(player);
        }
    }

    public void leave(final String player) {
        members.remove(player);
    }

    public int memberCount() {
        return members.size();
    }
}
