package ru.yandex.webmaster3.core.util.qloud;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.logstash.logback.encoder.LogstashEncoder;
import net.logstash.logback.fieldnames.LogstashFieldNames;

import java.util.HashMap;
import java.util.Map;

public class QloudRemoteEncoder extends LogstashEncoder {
    private static final ObjectMapper JSON_MAPPER = new ObjectMapper();

    public QloudRemoteEncoder(final Map<String, String> env) {
        super();

        final LogstashFieldNames fieldNames = new LogstashFieldNames();
        fieldNames.setThread("threadName");
        fieldNames.setLogger("loggerName");
        fieldNames.setLevelValue("level");
        fieldNames.setLevel("levelStr");
        fieldNames.setStackTrace("stackTrace");
        fieldNames.setMdc("@fields");

        this.setFieldNames(fieldNames);
        this.setIncludeMdc(true);
        this.setIncludeContext(false);
        final Map<String, String> customFields = new HashMap<>();
        customFields.put("host", env.get("QLOUD_HOSTNAME"));
        customFields.put("qloud_project", env.get("QLOUD_PROJECT"));
        customFields.put("qloud_application", env.get("QLOUD_APPLICATION"));
        customFields.put("qloud_environment", env.get("QLOUD_ENVIRONMENT"));
        customFields.put("qloud_component", env.get("QLOUD_COMPONENT"));

        if (env.containsKey("QLOUD_INSTANCE")) {
            customFields.put("qloud_instance", env.get("QLOUD_INSTANCE"));
        }

        try {
            setCustomFields(JSON_MAPPER.writeValueAsString(customFields));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Can't add custom fields to appender", e);
        }
    }
}
