package graphql.normalized;

import graphql.Internal;
import graphql.execution.directives.QueryAppliedDirective;
import graphql.language.VariableDefinition;
import org.jspecify.annotations.Nullable;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static graphql.normalized.ValueToVariableValueCompiler.normalizedInputValueToVariable;

/**
 * This accumulator class decides on whether to create a variable for a query argument and if so it tracks what variables were made.
 * The {@link ExecutableNormalizedOperationToAstCompiler} then uses all the variables when it compiles the final document.
 */
@Internal
public class VariableAccumulator {

    private final List<VariableValueWithDefinition> valueWithDefinitions;
    @Nullable
    private final VariablePredicate variablePredicate;

    public VariableAccumulator(@Nullable VariablePredicate variablePredicate) {
        this.variablePredicate = variablePredicate;
        valueWithDefinitions = new ArrayList<>();
    }

    public boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, QueryAppliedDirective queryAppliedDirective, String argName, NormalizedInputValue normalizedInputValue) {
        // when a variable is used on the argument to a query directive then the queryAppliedDirective will be nonnull.
        // otherwise it must be a field argument
        if (queryAppliedDirective != null) {
            return variablePredicate != null && variablePredicate.shouldMakeVariable(executableNormalizedField, queryAppliedDirective, argName, normalizedInputValue);
        } else {
            return variablePredicate != null && variablePredicate.shouldMakeVariable(executableNormalizedField, argName, normalizedInputValue);
        }
    }

    public VariableValueWithDefinition accumulateVariable(NormalizedInputValue normalizedInputValue) {
        VariableValueWithDefinition variableWithDefinition = normalizedInputValueToVariable(normalizedInputValue, getAccumulatedSize());
        valueWithDefinitions.add(variableWithDefinition);
        return variableWithDefinition;
    }

    public int getAccumulatedSize() {
        return valueWithDefinitions.size();
    }

    /**
     * @return the variable definitions that would go on the operation declaration
     */
    public List<VariableDefinition> getVariableDefinitions() {
        return valueWithDefinitions.stream().map(VariableValueWithDefinition::getDefinition).collect(Collectors.toList());
    }

    /**
     * @return the map of variable names to variable values
     */
    public Map<String, Object> getVariablesMap() {
        Map<String, Object> map = new LinkedHashMap<>();
        valueWithDefinitions.forEach(variableWithDefinition -> {
            String name = variableWithDefinition.getDefinition().getName();
            map.put(name, variableWithDefinition.getValue());
        });
        return map;
    }
}
