package com.mercury.chat.client.protocol.impl;

import static com.mercury.chat.common.MessageType.LOGIN;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import io.netty.channel.Channel;

import com.mercury.chat.client.json.MessageBox;
import com.mercury.chat.client.protocol.Connection;
import com.mercury.chat.client.protocol.LoginAuthHandler;
import com.mercury.chat.client.protocol.Session;
import com.mercury.chat.common.struct.protocol.Header;
import com.mercury.chat.common.struct.protocol.Message;
import com.mercury.chat.user.entity.User;

public class ConnectionImpl implements Connection{
	
	static final Logger logger = LogManager.getLogger(ConnectionImpl.class);

	private Channel channel;
	
	public ConnectionImpl() {
		super();
	}
	
	public ConnectionImpl channel(Channel channel){
		this.channel = channel;
		return this;
	}
	
	@Override
	public Session login(String userId, String password) {
		try {
			Message message = new Message().header(new Header().type(LOGIN.value())).body(new User(userId,password));
			channel.writeAndFlush(message).sync();//send login request to chat service
			MessageBox loginMessageBox = channel.pipeline().get(LoginAuthHandler.class).getLoginMessageBox();
			Message responseMsg = loginMessageBox.get();//wait until receive the login response.
			logger.info(responseMsg);
		} catch (InterruptedException e) {
			logger.error(e);
			return null;
		}
		return new SessionImpl(channel);
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean isClosed() {
		// TODO Auto-generated method stub
		return false;
	}
	
}

@@ -726,16 +726,55 @@
 lass);%0D%0A
+%09%0D%0A%09private volatile boolean closed;%0D%0A%09
 %0D%0A%09priva
@@ -1597,42 +1597,116 @@
 %0D%0A%09%09
-// TODO Auto-generated method stub
+try %7B%0D%0A%09%09%09channel.close().sync();%0D%0A%09%09%09closed = true;%0D%0A%09%09%7D catch (InterruptedException e) %7B%0D%0A%09%09%09//ignore%0D%0A%09%09%7D
 %0D%0A%09%09
@@ -1759,46 +1759,8 @@
  %7B%0D%0A
-%09%09// TODO Auto-generated method stub%0D%0A
 %09%09re
@@ -1768,13 +1768,14 @@
 urn 
-fal
+clo
 se
+d
 ;%0D%0A%09

add the close and isClosed method implementaion.