#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright © 2017 fishcried(tianqing.w@gmail.com)
#
import base64
import json
import socket
import time
import urllib2


class MetricSample(object):
    def __init__(self,
                 endpoint=socket.gethostname(),
                 timestamp=int(time.time()),
                 step=60,
                 counter_type="GAUGE",
                 tags=None,
                 metric=None,
                 value=None):
        self.endpoint = endpoint
        self.timestamp = timestamp
        self.step = step
        self.counter_type = counter_type
        self.tags = tags
        self.metric = metric
        self.value = value
        super(MetricSample, self).__init__()

    def to_dict(self):
        return {'endpoint': self.endpoint,
                'timestamp': self.timestamp,
                'step': self.step,
                'counterType': self.counter_type,
                'metric': self.metric,
                'value': self.value
                }

##########################################
# 'rabbitmq.messages.publish_rate',
# 'rabbitmq.messages.ack_rate',
# 'rabbitmq.messages.confirm_rate',
# 'rabbitmq.messages.deliver_rate',
# 'rabbitmq.messages.total_count',
# 'rabbitmq.messages.ready_count',
# 'rabbitmq.messages.unack_count',
# 'rabbitmq.consumers',
# 'rabbitmq.queues',
# 'rabbitmq.exchanges',
# 'rabbitmq.connections',
# 'rabbitmq.channels',
##########################################


def main():
    ip = '{{ hostip }}'
    request = urllib2.Request("http://%s:15672/api/overview" % ip)
    # see #issue4
    base64string = base64.b64encode(
        '{{ rabbitmq_user }}:{{ rabbitmq_password }}')
    request.add_header("Authorization", "Basic %s" % base64string)
    result = urllib2.urlopen(request)
    data = json.loads(result.read())

    post_data = []
    timestamp = int(time.time())

    # Get message stats
    message_stats = data['message_stats']

    post_data.append(MetricSample(
        endpoint=ip,
        timestamp=timestamp,
        metric='rabbitmq.messages.publish_rate',
        value=int(message_stats['publish_details']['rate'])).to_dict())

    post_data.append(MetricSample(
        endpoint=ip,
        timestamp=timestamp,
        metric='rabbitmq.messages.ack_rate',
        value=int(message_stats['ack_details']['rate'])).to_dict())

    if hasattr(message_stats, 'confirm_details'):
        post_data.append(MetricSample(
            endpoint=ip,
            timestamp=timestamp,
            metric='rabbitmq.messages.confirm_rate',
            value=int(message_stats['confirm_details']['rate'])).to_dict())

    post_data.append(MetricSample(
        endpoint=ip,
        timestamp=timestamp,
        metric='rabbitmq.messages.deliver_rate',
        value=int(message_stats['deliver_details']['rate'])).to_dict())

    # Get queue total
    queue_totals = data['queue_totals']
    post_data.append(MetricSample(
        endpoint=ip,
        timestamp=timestamp,
        metric='rabbitmq.messages.total_count',
        value=int(queue_totals['messages'])).to_dict())

    post_data.append(MetricSample(
        endpoint=ip,
        timestamp=timestamp,
        metric='rabbitmq.messages.ready_count',
        value=int(queue_totals['messages_ready'])).to_dict())
    post_data.append(MetricSample(
        endpoint=ip,
        timestamp=timestamp,
        metric='rabbitmq.messages.unack_count',
        value=int(queue_totals['messages_unacknowledged'])).to_dict())

    object_totals = data['object_totals']
    post_data.append(MetricSample(
        endpoint=ip,
        timestamp=timestamp,
        metric='rabbitmq.consumers',
        value=int(object_totals['consumers'])).to_dict())
    post_data.append(MetricSample(
        endpoint=ip,
        timestamp=timestamp,
        metric='rabbitmq.queues',
        value=int(object_totals['queues'])).to_dict())

    post_data.append(MetricSample(
        endpoint=ip,
        timestamp=timestamp,
        metric='rabbitmq.exchanges',
        value=int(object_totals['exchanges'])).to_dict())

    post_data.append(MetricSample(
        endpoint=ip,
        timestamp=timestamp,
        metric='rabbitmq.connections',
        value=int(object_totals['connections'])).to_dict())
    post_data.append(MetricSample(
        endpoint=ip,
        timestamp=timestamp,
        metric='rabbitmq.channels',
        value=int(object_totals['channels'])).to_dict())

    print json.dumps(post_data, indent=4)

    opener = urllib2.build_opener(urllib2.HTTPHandler())
    request = urllib2.Request('http://127.0.0.1:1988/v1/push',
                              data=json.dumps(post_data))
    request.add_header("Content-Type", 'application/json')
    request.get_method = lambda: 'POST'
    try:
        connection = opener.open(request)
    except urllib2.HTTPError as e:
        connection = e

    if connection.code == 200:
        print connection.read()
    else:
        print '{"err":1,"msg":"%s"}' % connection

if __name__ == '__main__':
    main()
