package ru.yandex.qe.dispenser.metrics;

import java.util.concurrent.atomic.AtomicLong;

import ch.qos.logback.core.status.Status;
import ch.qos.logback.core.status.StatusListener;

import ru.yandex.monlib.metrics.labels.Labels;
import ru.yandex.monlib.metrics.registry.MetricRegistry;

public class LogbackDropListener implements StatusListener {

    private final AtomicLong droppedEvents = new AtomicLong();
    private final AtomicLong truncatedEvents = new AtomicLong();

    public LogbackDropListener(MetricRegistry metricRegistry) {
        metricRegistry.lazyGaugeInt64("logback.event_rate", Labels.of("event_type", "drop"),
                droppedEvents::longValue);
        metricRegistry.lazyGaugeInt64("logback.event_rate", Labels.of("event_type", "truncate"),
                droppedEvents::longValue);
    }

    @Override
    public void addStatusEvent(Status status) {
        String msg = status.getMessage();
        if (msg.startsWith("Dropped")) {
            count(msg, droppedEvents);
        } else if (msg.startsWith("Truncated")) {
            count(msg, truncatedEvents);
        }
    }

    private void count(final String msg, final AtomicLong counter) {
        final String[] parts = msg.split(" ", 3);
        if (parts.length == 3) {
            counter.set(Long.parseLong(parts[1]));
        }
    }

}
