// subscribes an SUser to appropriate que 
// for messages to that SUser

/*
Implements the same API as comet.js
init : function () {
connect : function() {
disconnect : function () {
publish : function (msg) {
subscribe : function(suser_uuid) {
unsubscribe : function(suser_uuid) {
delegate : function (type) {
call : function (method, value) {
debug : function (msg) {
*/

POKE.comet = function () {
    
	var myExchange;
	var myQueue;
	var routing_key;
	var declareCount = 0;
	
    var pub = {
 
        init : function () {
        },

        connect : function() {
            // setup the swf and populate it with flashvars
            //Initialize the proxy
            pub.debug("Connecting");
            AMQPClient.initialize({
				connection: {
				    user: 'guest',
				    pass: 'guest',
				    vhost	: "/",
					host: POKE.settings.RABBITMQ_SERVER,
                    port: POKE.settings.AMQP_PORT
				},
				logger		: console,
				logLevel    : 1,
				swfPath		: POKE.settings.AMQP_SWF_URL,
				policy_host : POKE.settings.POLICY_HOST,
				policy_port : POKE.settings.POLICY_PORT,
				id 			: 'amqp_swf'
			});
			AMQPClient.addListener("ready", pub.client_ready);
        },

		client_ready: function(){
			pub.debug("AMQPClient ready");
			pub.flash_app().onconnectedframe();
		},
		
		flash_app: function(){
			return $("#flash_content").get(0);
		},

        disconnect : function () {
			pub.debug("Disconnecting AMQP");
			// myExchange.listeners = {};
			// myQueue.listeners = {};
			AMQPClient.listeners = {};
			AMQPClient.disconnect();
            myQueue.listeners = {};
            myExchange.listeners = {};
			declareCount = 0;
			pub.flash_app().onclose();
			$.post(POKE.settings.API_DESTORY_QUEUE_URL, { 'uuid': routing_key  });
        },

		exchangeCallback: function(msg){
			json_message = JSON.stringify(msg.data);
			pub.debug("JSON MESSAGE:");
			pub.debug(json_message);
			pub.flash_app().onmessageframe({'body': json_message});
		},

        subscribe : function(suser_uuid) {
			//Declare a queue and subscribe to it.
			//The callback is called when messages
			//are delivered to the queue.
			pub.debug("AMQP: subscribe on " + suser_uuid);
			routing_key = suser_uuid;

			myExchange = new Exchange({
				declare: {
					exchange	: POKE.settings.AMQP_NOTIFICATION_EXCHANGE,
					type		: "direct"
				}
			});

			myQueue = new MessageQueue({
				declare: {
					queue		: POKE.settings.AMQP_NOTIFICATION_QUEUE + "_" + routing_key,
					auto_delete	: true
				}
			});

			// when the queue is declared, bind the exchange to it, so that
			// messages published to the exchange are delivered to the queue
			// and the javascript callback is called
			myQueue.addListener("declared", pub.handleDeclarations, this);
			myExchange.addListener("declared", pub.handleDeclarations, this);
			AMQPClient.registerExchange(myExchange);
        },

		handleDeclarations: function(){
			declareCount++;
            pub.debug("handleDeclarations, currently " + declareCount);
			if(declareCount == 2){
                pub.debug("BINDING: Making queue declarations");
				myQueue.bind(myExchange, routing_key, pub.exchangeCallback);
			}
		},

        on_message : function (msg) {
            pub.debug('MESSAGE HERE');
            pub.debug('message');
        },

		unsubscribe: function(){
			pub.debug("AMQP Unsubscribe");
		},

        on_exchange : function (msg) {
            pub.debug('EXCHANGE HERE');
            pub.debug(msg.data);
			alert("oh hai");
        },

        call : function (method, value) {
            if (value){
                pub.debug(method + ' ' + value.body);
            }else{
                pub.debug(method);
                value = '';
            }
            var flash = document.getElementById('flash_content');
            if(flash){
                flash[method](value);
            }            
        },
        debug : function (msg) {
            if(POKE.settings.DEBUG) {
                console.log('comet: ' + msg);
            }
        }
    };
    
    // POKE.init.add_on_dom_ready();
    
    return pub;
    
}();
