package ru.yandex.webmaster3.storage.util.ydb.query;

import java.util.Map;
import java.util.Set;

import com.yandex.ydb.table.values.Type;
import com.yandex.ydb.table.values.Value;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.NotNull;

/**
 * ishalaru
 * 17.07.2020
 **/
public class Assignment extends Utils.Appendeable implements ParametersDeclaration {
    private String name;
    private final Type type;
    private final Value value;
    private int index;

    public Assignment(@NotNull String name, @NotNull Object value) {
        this.name = name;
        Pair<Type, Value> pair = Utils.defineType(value);
        this.type = pair.getKey();
        this.value = pair.getValue();
    }

    public Assignment(@NotNull String name, @NotNull Type type, @NotNull Value value) {
        this.name = name;
        this.type = type;
        this.value = value;
    }

    @Override
    public StringBuilder appendDeclaration(StringBuilder sb, Set<Integer> declaredParameters) {
        if (!declaredParameters.contains(index)) {
            declaredParameters.add(index);
            return sb.append("DECLARE ")
                    .append(Utils.generateParameterName(index))
                    .append(" as `")
                    .append(type.toString())
                    .append("`;\n");
        }
        return sb;
    }

    public void putParameter(Map<String, Value> map) {
        map.put(Utils.generateParameterName(index), value);
    }

    public int initIndex(int index) {
        this.index = index;
        return index + 1;
    }

    @Override
    public void appendTo(StringBuilder sb) {
        Utils.appendName(name, sb);
        sb.append(" = ");
        Utils.appendValue(index, sb);
    }
}
