
from __future__ import absolute_import
from __future__ import division

import six
import socket

_client = None


def start(address, port=8125):
    global _client
    if _client is None:
        _client = _StatsClient(address, port=port)


def stop():
    global _client
    if _client is not None:
        _client.close()


def send(report):
    for name, value in six.iteritems(report):
        _client.gauge(name, value)


class _StatsClient(object):
    def __init__(self, host, port=8125, maxudpsize=512, ipv6=False):
        fam = socket.AF_INET6 if ipv6 else socket.AF_INET
        family, _, _, _, addr = socket.getaddrinfo(
            host, port, fam, socket.SOCK_DGRAM)[0]
        self._addr = addr
        self._sock = socket.socket(family, socket.SOCK_DGRAM)
        self._maxudpsize = maxudpsize

    def _send(self, data):
        try:
            self._sock.sendto(data, self._addr)
        except socket.error:
            pass

    def close(self):
        self._sock.close()

    def gauge(self, stat, value):
        self._send('%s:%s|g' % (stat, value))
