#!/usr/bin/env python
#-*- coding:utf-8 -*-
# FIXME: this should use the egg once its complete for now we are doing some sys.path
# changes, make this work
import sys, os
sys.path.append(os.path.abspath(".."))

import logging
from haigha import Connection, Message
from haigha import event
import signal

if len(sys.argv)!=4:
  print 'Usage: example <user> <password> <vhost>'
  sys.exit(1)

debug = 2
level = logging.DEBUG if debug else logging.INFO

# Setup logging
logging.basicConfig(level=level, format="[%(levelname)s %(asctime)s] %(message)s" )
logger = logging.getLogger('haigha')

def sigint_cb(*args):
  """callback when we get a SIGINT."""
  logger.info( 'canceling consumer ...' )
  ch.basic.cancel( consumer=consumer, cb=consume_cancelled )
  event.timeout( 2, consume_cancel_fail )

def consume_cancel_fail():
  logger.error( 'failed to cancel consumer' )
  event.abort()

def consume_cancelled():
  logger.info( 'cancelled' )
  event.abort()

event.signal( signal.SIGINT, sigint_cb )


# Create a connection
logger.info( 'connecting ...' )
c = Connection(logger=logger, debug=debug, user=sys.argv[1], password=sys.argv[2], vhost=sys.argv[3], heartbeat=3)

def consumer(msg):
  logger.info( 'consuming %s', msg )
  #ch.basic.cancel( consumer=consumer )

  #ch.basic.publish( Message(body='haigha sez hello'), exchange='foo', routing_key='no.matter' )
  #ch.publish_synchronous( Message(body='haigha sez hello'), exchange='foo', routing_key='no.matter', cb=msg_published )

def msg_published():
  logger.info( 'message published' )

ch = c.channel()
ch.exchange.declare( 'foo', 'topic' )
ch.queue.declare( 'bar' )
ch.queue.bind(  'bar', 'foo', 'hello.world' )
ch.basic.consume( 'bar', consumer )


ch.publish_synchronous( Message(body='haigha sez hello', application_headers={'cat':'dog'}), exchange='foo', routing_key='hello.world', cb=msg_published )

#ch.queue.delete( 'bar' )
#ch.exchange.delete( 'foo' )

event.dispatch()
