/*
 * IRCChannel.java
 * IRCCore
 *
 * Created by tarchan on Aug 07, 2006.
 * Copyright (c) 2006 tarchan. All rights reserved.
 */
package com.mac.tarchan.irc;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.builder.ToStringBuilder;

/**
 * IRCChannel
 * 
 * @author tarchan
 * @author nori090
 */
public class IRCChannel {
    private IRCNetwork net;

    private String name;

    private ConcurrentHashMap<IRCUser, IRCChannelUser> users = new ConcurrentHashMap<IRCUser, IRCChannelUser>();

    public IRCChannel( String channelName ) {
        name = channelName;
    }

    public void setNetwork( IRCNetwork network ) {
        if ( net != null )
            throw new RuntimeException( "already exsists: " + net );
        net = network;
    }

    public String getName() {
        return name;
    }

    public IRCChannelUser[] getUsers() {
        return (IRCChannelUser[]) users.values().toArray( new IRCChannelUser[0] );
    }

    public boolean containsUser( String nick ) {
        IRCUser user = net.findUser( nick );
        return containsUser( user );
    }

    public boolean containsUser( IRCUser user ) {
        return users.containsKey( user );
    }

    public void addUser( IRCUser user ) {
        if ( user == null )
            throw new NullPointerException( "user" );
        if ( !containsUser( user ) ) {
            users.put( user, new IRCChannelUser( this, user ) );
            user.join( this );
        }
    }

    public IRCUser removeUser( IRCUser user ) {
        return users.remove( user ) != null ? user : null;
    }

    public int getUserCount() {
        return users.size();
    }

    public String toString() {
        return new ToStringBuilder( this ).append( "name", name ).append( "users", users ).toString();
    }
}
