try:
    import json
except ImportError:
    import simplejson as json

from onapp.cdn.routing import Processor
import onapp.lib.log as log

def on_message(channel, method, header, body):
    log.debug('Message body: %s' % body)
    try:
        __process_message(__get_payload(body))
    except Exception, error:
        log.error('Processing message failed! Message body: [%s], error: [%s]' % (body, error))
    finally:
        __ack(channel, method.delivery_tag)

def __process_message(payload):
    if not isinstance(payload, dict):
        log.error('Expected message body to be dict. Received: %s' % payload)
        return
    component = payload.get('component')
    if component == 'cdn':
        __cdn_reaction(payload)
    elif component == 'management':
        __mgmt_reaction(payload)

def __get_payload(body):
    try:
        return json.loads(body)
    except (ValueError, TypeError), e:
        log.error('Failed to parse message body: %s' % e)

def __ack(channel, delivery_tag):
    channel.basic_ack(delivery_tag)

def __mgmt_reaction(payload):
    if payload.get('manage') == 'quit':
        raise KeyboardInterrupt

def __cdn_reaction(payload):
    event = payload.get('event')
    if event == 'alter':
        Processor(payload).update()
    elif event == 'destruction':
        Processor(payload).cleanup()
