// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION Or its licensors retain all intellectual property
// Or proprietary rights in nor to this software, related documentation
// Or any modifications thereto.  Any use, reproduction, disclosure or
// distribution of this software Or related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#include <OgnOrDatabase.h>
#include <omni/graph/core/ogn/ComputeHelpers.h>
#include <carb/logging/Log.h>
#include "ResolveBooleanOpAttributes.h"
#include "OperatorComputeWrapper.h"

namespace omni {
namespace graph {
namespace nodes {
    
// unnamed namespace to avoid multiple declaration when linking
namespace {

/**
 * Boolean OR on two inputs.
 * If a and b are arrays, OR operations will be performed pair-wise. Sizes of a and b must match.
 * If only one input is an array, the other input will be broadcast to the size of the array.
 * Returns an array of booleans if either input is an array, otherwise returning a boolean.
 *
 * @param db: database object
 * @return True if we can get a result properly, false if not
 */

bool tryCompute(OgnOrDatabase& db)
{
    auto const& dynamicInputs = db.getDynamicInputs();
    if (dynamicInputs.empty())
    {
        auto functor = [](bool const& a, bool const& b, bool& result)
        {
            result = static_cast<bool>(a || b);
        };
        return ogn::compute::tryComputeWithArrayBroadcasting<bool,bool,bool>(db.inputs.a(), db.inputs.b(), db.outputs.result(), functor);
    }
    else
    {
        std::vector<ogn::InputAttribute> inputs{ db.inputs.a(), db.inputs.b() };
        inputs.reserve(dynamicInputs.size() + 2);
        for (auto const& input : dynamicInputs)
            inputs.emplace_back(input());

        auto functor = [](bool const& a, bool& result)
        {
            result = static_cast<bool>(result || a);
        };
        return ogn::compute::tryComputeInputsWithArrayBroadcasting<bool>(inputs, db.outputs.result(), functor);
    }
}
} // namespace

class OgnOr
{
public:
    static bool compute(OgnOrDatabase& db)
    {
        return tryComputeOperator<OgnOrDatabase>(tryCompute, db);
    }

    static void onConnectionTypeResolve(const NodeObj& node)
    {
        resolveBooleanOpDynamicAttributes(node, outputs::result.token());
    }
};

REGISTER_OGN_NODE()

} // namespace nodes
} // namespace graph
} // namespace omni
