package chat;
import java.io.IOException;
import java.io.ObjectOutputStream;
import chat.connection.AbstractChatConnection;
import main.PeerProtocol;
import common.connection.ConnectionWriterInterface;
import ui.tabs.PrivateChatTab;
import static main.ClientMain.*;
public class PrivateChatSession implements MessageSenderInterface
{
private AbstractChatConnection connection;
private volatile String nickname;
private PrivateChatTab tab;
private volatile boolean appeared;
private MessageBufferThread sender;
public PrivateChatSession(AbstractChatConnection connection)
{
this.connection = connection;
nickname = "Unknown";
sender = new MessageBufferThread(this);
tab = new PrivateChatTab(this);
appeared = false;
}
public String getNickname()
{
return nickname;
}
public void setNickname(String nickname)
{
this.nickname = nickname;
tab.getForm().setTitle(nickname);
}
public void show()
{
appeared = true;
getMainFrame().addDynamicTab(tab, "Chat");
tab.getForm().enable();
}
public void activate()
{
getMainFrame().activateTab(tab);
}
public synchronized void logMessage(String message)
{
tab.getForm().logMessage(nickname, message);
if (!appeared)
{
show();
}
tab.flash();
}
public void queueMessage(String message)
{
sender.queueMessage(message);
}
public void sendMessage(final String message)
{
int protocolId = PeerProtocol.PROTOCOL_CHAT;
int opcode = PeerProtocol.Chat.OP_MESSAGE;
connection.send(protocolId, opcode, new ConnectionWriterInterface()
{
public void run(ObjectOutputStream os) throws IOException
{
os.writeUTF(message);
}
});
}
private void disable()
{
tab.getForm().disable();
sender.terminate();
}
public void notifyTerminated()
{
disable();
if (appeared)
{
notifyUserOfTermination();
}
}
public void terminate()
{
disable();
connection.terminate();
}
private void notifyUserOfTermination()
{
tab.getForm().logMessage("", nickname + " has closed the conversation.");
}
}