package com.ht.web.cometd.service;

import org.cometd.bayeux.Channel;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.client.ClientSession;
import org.cometd.java.annotation.Listener;
import org.cometd.java.annotation.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ht.util.UserSession;

@org.cometd.java.annotation.Service
public class BaseService {
	private static final Logger log = LoggerFactory
			.getLogger(BaseService.class);

	@Session
	private ClientSession bayeuxClient;
	private boolean connected = false;

	@Listener(Channel.META_CONNECT)
	public void metaConnect(Message connect) {
		if (!connect.isSuccessful()) {
			if (connected) {

				log.info("已与Cometd服务器断开连接.");
				connected = false;
				bayeuxClient.batch(new Runnable() {

					@Override
					public void run() {
						UserSession.INSTANCE.setUser(
								null);
						bayeuxClient.handshake();
					}
				});
			}
		} else if (!connected){
				connected = true;
				log.info("已与Cometd服务器建立连接.");
		}
	}
}