package de.ctdo.crashtest.irc;

import de.ctdo.crashtest.log.ILogger;
import de.ctdo.crashtest.log.Logger;
import jerklib.Channel;
import jerklib.ConnectionManager;
import jerklib.ProfileImpl;
import jerklib.Session;
import jerklib.events.ChannelMsgEvent;
import jerklib.events.ConnectionCompleteEvent;
import jerklib.events.IRCEvent;
import jerklib.events.JoinCompleteEvent;

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

/**
 * IRC Client wrapper
 * simplifies communication with the irc channel
 */
public class IrcClient implements IIrcClient, jerklib.events.listeners.IRCEventListener, ILogger {
    private final List<IRCEventListener> listenerListIRC = new ArrayList<IRCEventListener>();
    private final Session ircsession;
    private final String channel;

    public IrcClient(String nick, String channel, String server) {
        this.channel = channel;
        ConnectionManager ircConnection = new ConnectionManager(new ProfileImpl(nick,nick, nick+2, nick+3));
        ircsession = ircConnection.requestConnection(server);
        ircsession.addIRCEventListener(this);
    }

    @Override
    public void recieveEvent(IRCEvent ircEvent) {

        if(ircEvent instanceof ConnectionCompleteEvent) {
            ircEvent.getSession().joinChannel(channel);
        }
        else if (ircEvent instanceof JoinCompleteEvent) {
            JoinCompleteEvent jce = (JoinCompleteEvent) ircEvent;
            jce.getChannel().say("hello master. what's your order?");
            
            Logger logger = Logger.getInstance();
            logger.addLogger(this);
        }
        else if(ircEvent instanceof ChannelMsgEvent) {
            ChannelMsgEvent cme = (ChannelMsgEvent)ircEvent;
            
            String message = cme.getMessage();
            final String nick = ircsession.getNick();
            
            if(message.startsWith(nick) || message.startsWith(">")) {
                if(message.startsWith(nick)) {
                    message = message.substring(Math.max(nick.length(), message.indexOf(":")+1));
                }
                else {
                    message = message.substring(1);
                }

                message = message.trim();

                for(IRCEventListener listenerIRC : listenerListIRC) {
                    listenerIRC.handleMessage(message);
                }
            }
        }
    }

    @Override
    public void log(String message) {
        say("LOG: " + message);
    }

    @Override
    public void say(String message) {
        if(ircsession != null) {
            for(Channel chan: ircsession.getChannels()) {
                chan.say(message);
            }
        }
    }

    @Override
    public void addListener(final IRCEventListener listenerIRC) {
        listenerListIRC.add(listenerIRC);
    }
}
