#include "JsonLogic.h"

namespace json_logic
{
    Json JsonLogic::operation_array_map(JsonArrayView values, JsonView data) const
    {
        if (values.size() != 2)
            return Fail(__FUNCTION__, "Expected 2 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 result;
        auto output = result.to<ArduinoJson::JsonArray>();
        for (JsonView item : input.as<ArduinoJson::JsonArrayConst>())
        {
            const Json mapped = ApplyInternal(values[1], item);
            if (HasError()) return Json{};
            output.add(mapped);
        }
        return result;
    }
}
