package ru.yandex.webmaster3.monitoring.solomon.trigger.expressions;

import ru.yandex.webmaster3.core.solomon.metric.SolomonKey;

import java.util.stream.Collectors;

/**
 * Created by Oleg Bazdyrev on 07/08/2018.
 */
public class SolomonProgramBuilder {

    private StringBuilder value = new StringBuilder(1024);

    public SolomonProgramBuilder() {
        value.append("// autogenerated by webmaster3 SolomonProgramBuilder\n\n");
    }

    private static String renderSelectorForExpression(SolomonKey key) {
        return key.getLabels().entrySet()
                .stream()
                .map(entry -> "  " + entry.getKey() + "='" + entry.getValue() + "'")
                .collect(Collectors.joining(",\n"));
    }

    public SolomonProgramBuilder addVariable(String name, SolomonKey labels) {
        value.append("let ").append(name).append(" = {\n");
        value.append(renderSelectorForExpression(labels));
        value.append("\n};\n\n");
        return this;
    }

    public SolomonProgramBuilder addExpression(String name, SolomonTriggerExpression expression) {
        value.append("let ").append(name).append(" = ").append(expression.renderExpression()).append(";\n");
        return this;
    }

    public String build() {
        return value.toString();
    }

}
