// Copyright (c) 2014, Christopher "blay09" Baker
// All rights reserved.

package net.blay09.mods.eirairc.handler;

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

import net.blay09.mods.eirairc.api.IRCChannel;
import net.blay09.mods.eirairc.api.IRCContext;
import net.blay09.mods.eirairc.api.IRCUser;

public class ChatSessionHandler {

	private IRCContext chatTarget = null;
	private final List<IRCChannel> validTargetChannels = new ArrayList<IRCChannel>();
	private final List<IRCUser> validTargetUsers = new ArrayList<IRCUser>();
	private int targetChannelIdx = 0;
	private int targetUserIdx = -1;

	public void addTargetUser(IRCUser user) {
		if(!validTargetUsers.contains(user)) {
			validTargetUsers.add(user);
		}
	}

	public void addTargetChannel(IRCChannel channel) {
		if(!validTargetChannels.contains(channel)) {
			validTargetChannels.add(channel);
		}
	}

	public void removeTargetUser(IRCUser user) {
		validTargetUsers.remove(user);
	}

	public void removeTargetChannel(IRCChannel channel) {
		validTargetChannels.remove(channel);
	}

	public void setChatTarget(IRCContext chatTarget) {
		this.chatTarget = chatTarget;
		if(chatTarget instanceof IRCChannel) {
			targetUserIdx = -1;
			targetChannelIdx = validTargetChannels.indexOf(chatTarget);
		} else if(chatTarget instanceof IRCUser) {
			targetChannelIdx = 0;
			targetChannelIdx = validTargetUsers.indexOf(chatTarget);
		}
	}

	public IRCContext getChatTarget() {
		return chatTarget;
	}

	public IRCContext getNextTarget(boolean users) {
		if(users) {
			if(validTargetUsers.isEmpty()) {
				return null;
			}
			targetUserIdx++;
			if(targetUserIdx >= validTargetUsers.size()) {
				targetUserIdx = 0;
			}
			return validTargetUsers.get(targetUserIdx);
		} else {
			if(validTargetChannels.isEmpty()) {
				return null;
			}
			targetChannelIdx++;
			if(targetChannelIdx > validTargetChannels.size()) {
				targetChannelIdx = 0;
			}
			if(targetChannelIdx == 0) {
				return null;
			}
			return validTargetChannels.get(targetChannelIdx - 1);
		}
	}

	public boolean isMinecraftTarget() {
		return chatTarget == null;
	}
}

@@ -564,17 +564,18 @@
 elIdx = 
-0
+-1
 ;%0A%09priva
@@ -597,18 +597,17 @@
 erIdx = 
--1
+0
 ;%0A%0A%09publ
@@ -1193,18 +1193,17 @@
 erIdx = 
--1
+0
 ;%0A%09%09%09tar
@@ -1322,25 +1322,26 @@
 hannelIdx = 
-0
+-1
 ;%0A%09%09%09targetC
@@ -1331,39 +1331,36 @@
  = -1;%0A%09%09%09target
-Channel
+User
 Idx = validTarge
@@ -1843,16 +1843,17 @@
 nelIdx %3E
+=
  validTa
@@ -1894,25 +1894,26 @@
 hannelIdx = 
-0
+-1
 ;%0A%09%09%09%7D%0A%09%09%09if
@@ -1933,17 +1933,18 @@
 lIdx == 
-0
+-1
 ) %7B%0A%09%09%09%09
@@ -2015,12 +2015,8 @@
 lIdx
- - 1
 );%0A%09
@@ -2026,76 +2026,6 @@
 %09%7D%0A%0A
-%09public boolean isMinecraftTarget() %7B%0A%09%09return chatTarget == null;%0A%09%7D%0A
 %7D%0A

Fix ChatSessionHandler getting stuck on last channel and not moving back to Minecraft.