# coding=utf-8

"""
Collect statistics from Flume

#### Dependencies

 * urllib
 * json or simplejson

"""

import urllib.error
import urllib.request

import diamond.collector

try:
    import simplejson as json
except ImportError:
    import json


class FlumeCollector(diamond.collector.Collector):
    # items to collect
    _metrics_collect = {
        "CHANNEL": [
            "ChannelFillPercentage",
            "EventPutAttemptCount",
            "EventPutSuccessCount",
            "EventTakeAttemptCount",
            "EventTakeSuccessCount",
        ],
        "SINK": [
            "BatchCompleteCount",
            "BatchEmptyCount",
            "BatchUnderflowCount",
            "ConnectionClosedCount",
            "ConnectionCreatedCount",
            "ConnectionFailedCount",
            "EventDrainAttemptCount",
            "EventDrainSuccessCount",
        ],
        "SOURCE": [
            "AppendAcceptedCount",
            "AppendBatchAcceptedCount",
            "AppendBatchReceivedCount",
            "AppendReceivedCount",
            "EventAcceptedCount",
            "EventReceivedCount",
            "OpenConnectionCount",
        ],
    }

    def get_default_config_help(self):
        config_help = super(FlumeCollector, self).get_default_config_help()
        config_help.update(
            {
                "req_host": "Hostname",
                "req_port": "Port",
                "req_path": "Path",
            }
        )

        return config_help

    def get_default_config(self):
        """
        Returns the default collector settings
        """
        default_config = super(FlumeCollector, self).get_default_config()
        default_config["path"] = "flume"
        default_config["req_host"] = "localhost"
        default_config["req_port"] = 41414
        default_config["req_path"] = "/metrics"

        return default_config

    def collect(self):
        url = "http://{}:{}{}".format(
            self.config["req_host"], self.config["req_port"], self.config["req_path"]
        )

        try:
            resp = urllib.request.urlopen(url)

            try:
                j = json.loads(resp.read())
                resp.close()
            except Exception as e:
                resp.close()
                self.log.error("Cannot load json data: %s", e)

                return None
        except urllib.error.URLError as e:
            self.log.error("Failed to open url: %s", e)

            return None
        except Exception as e:
            self.log.error("Unknown error opening url: %s", e)

            return None

        for comp in iter(j.items()):
            comp_name = comp[0]
            comp_items = comp[1]
            comp_type = comp_items["Type"]

            for item in self._metrics_collect[comp_type]:
                if item.endswith("Count"):
                    metric_name = "{}.{}".format(comp_name, item[:-5])
                    metric_value = int(comp_items[item])
                    self.publish_counter(metric_name, metric_value)
                elif item.endswith("Percentage"):
                    metric_name = "{}.{}".format(comp_name, item)
                    metric_value = float(comp_items[item])
                    self.publish_gauge(metric_name, metric_value)
                else:
                    metric_name = item
                    metric_value = int(comp_items[item])
                    self.publish_gauge(metric_name, metric_value)
