#include "JsonLogic.h"

#include <unordered_set>

namespace json_logic
{
    Json JsonLogic::operation_data_missing_some(JsonArrayView values, JsonView data) const
    {
        if (values.size() != 2)
            return Fail(__FUNCTION__, "Expected 2 arguments, but received " +
                                          std::to_string(values.size()));
        if (!IsNumber(values[0]))
            return Fail(__FUNCTION__, "First argument must be a number");
        if (!values[1].is<ArduinoJson::JsonArrayConst>())
            return Fail(__FUNCTION__, "Second argument must be an array");

        const double minimum = ToDouble(values[0]);
        std::size_t found = 0;
        std::unordered_set<std::string> seen_found;
        std::unordered_set<std::string> seen_missing;
        Json result;
        auto missing = result.to<ArduinoJson::JsonArray>();

        for (JsonView value : values[1].as<ArduinoJson::JsonArrayConst>())
        {
            if (!value.is<const char*>()) continue;
            const std::string key = value.as<const char*>();
            Json resolved;
            if (TryResolveVariable(value, data, resolved))
            {
                if (seen_found.insert(key).second) ++found;
            }
            else if (seen_missing.insert(key).second)
            {
                missing.add(key);
            }
        }

        if (static_cast<double>(found) >= minimum) return MakeArray();
        return result;
    }
}
