#include "JsonLogic.h"

#include <cstring>

namespace json_logic
{
    Json JsonLogic::operation_array_string_in(JsonArrayView values, JsonView data) const
    {
        if (values.size() != 2)
            return Fail(__FUNCTION__, "Expected 2 arguments, but received " +
                                          std::to_string(values.size()));
        const Json search = ApplyInternal(values[0], data);
        if (HasError()) return Json{};
        const Json container = ApplyInternal(values[1], data);
        if (HasError()) return Json{};

        if (container.is<ArduinoJson::JsonArrayConst>())
        {
            for (JsonView item : container.as<ArduinoJson::JsonArrayConst>())
                if (JsonEqual(item, search)) return MakeBoolean(true);
            return MakeBoolean(false);
        }

        if (container.is<const char*>())
        {
            if (!search.is<const char*>())
                return Fail(__FUNCTION__,
                            "When the second argument is a string, the first one must also be a string");
            return MakeBoolean(std::strstr(container.as<const char*>(), search.as<const char*>()) != nullptr);
        }

        return Fail(__FUNCTION__, "Invalid arguments");
    }
}
