package com.ht.web.cometd;

import java.util.HashMap;

import org.cometd.bayeux.client.ClientSession;
import org.cometd.client.BayeuxClient;
import org.cometd.client.transport.ClientTransport;
import org.cometd.client.transport.LongPollingTransport;
import org.cometd.java.annotation.ClientAnnotationProcessor;
import org.eclipse.jetty.client.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ht.ui.MainApplication;
import com.ht.web.cometd.service.BaseService;
import com.ht.web.cometd.service.TagVarCometdService;

public enum CometdManager {
	INSTANCE;
	private final Logger log = LoggerFactory
			.getLogger(CometdManager.class);

	private HttpClient httpClient;
	private ClientSession bayeuxClient;

	private CometdManager() {

		httpClient = new HttpClient();
		// Here set up Jetty's HttpClient, for example:
		httpClient.setMaxConnectionsPerAddress(2);
		
	}
	
	public void start() {
		log.info("启动Cometd通讯服务。");
		
		try {
			httpClient.start();

			// Prepare the WebSocket transport
//			WebSocketClientFactory wsFactory = new WebSocketClientFactory();
//			wsFactory.start();
//			ClientTransport transport = new WebSocketTransport(null, wsFactory, null);
			
			ClientTransport transport = LongPollingTransport.create(
					new HashMap<String, Object>(), httpClient);

			bayeuxClient = new BayeuxClient("http://" + MainApplication.getMainApp().hostProperty().getValue() + "/cometd",
					transport);

			ClientAnnotationProcessor processor = new ClientAnnotationProcessor(
					bayeuxClient);

			varTagService = new TagVarCometdService();
//			indexTagService = new IndexTagService();

			// Process the annotated service
			processor.process(new BaseService());
			processor.process(varTagService);
//			processor.process(indexTagService);

			bayeuxClient.handshake();

			log.info("Cometd通讯服务已启动。");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void stop() {
		log.info("停止cometd服务.");
		if (bayeuxClient != null) {
			bayeuxClient.disconnect();
		}
		httpClient.destroy();
		log.info("cometd服务已停止.");
	}

	public TagVarCometdService getVarTagService() {
		return varTagService;
	}

//	public IndexTagService getIndexTagService() {
//		return indexTagService;
//	}

	private TagVarCometdService varTagService;
//	private IndexTagService indexTagService;
}
