#include "JsonLogic.h"

namespace json_logic
{
    Json JsonLogic::operation_array_reduce(JsonArrayView values, JsonView data) const
    {
        if (values.size() != 3)
            return Fail(__FUNCTION__, "Expected 3 arguments, but received " +
                                          std::to_string(values.size()));
        const Json input = ApplyInternal(values[0], data);
        if (HasError()) return Json{};
        if (!input.is<ArduinoJson::JsonArrayConst>())
            return Fail(__FUNCTION__, "First argument must be an array");
        if (!IsLogic(values[1]))
            return Fail(__FUNCTION__, "Second argument must be a logic object");

        Json accumulator = ApplyInternal(values[2], data);
        if (HasError()) return Json{};
        for (JsonView current : input.as<ArduinoJson::JsonArrayConst>())
        {
            Json scope;
            auto object = scope.to<ArduinoJson::JsonObject>();
            object["accumulator"].set(accumulator);
            object["current"].set(current);
            accumulator = ApplyInternal(values[1], scope);
            if (HasError()) return Json{};
        }
        return accumulator;
    }
}
