#include <AK/Utf16FlyString.h>
#include <LibJS/Runtime/ArrayPrototype.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Bindings/NamedNodeMap.h>
#include <LibWeb/DOM/Attr.h>
#include <LibWeb/DOM/NamedNodeMap.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

void NamedNodeMapConstructor::initialize(JS::Realm& realm, JS::NativeFunction& object)
{
    auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;

    
    object.define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "NamedNodeMap"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<NamedNodeMapPrototype>(realm, "NamedNodeMap"_fly_string), 0);
}

JS::ThrowCompletionOr<GC::Ref<JS::Object>> NamedNodeMapConstructor::construct([[maybe_unused]] InterfaceConstructor& constructor, [[maybe_unused]] JS::FunctionObject& new_target)
{
    WebIDL::log_trace(constructor.vm(), "NamedNodeMapConstructor::construct");
    return constructor.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, "NamedNodeMap");
}

GC_DEFINE_ALLOCATOR(NamedNodeMapPrototype);

NamedNodeMapPrototype::NamedNodeMapPrototype([[maybe_unused]] JS::Realm& realm)
    : Object(ConstructWithPrototypeTag::Tag, realm.intrinsics().object_prototype())
{
}

NamedNodeMapPrototype::~NamedNodeMapPrototype()
{
}


void NamedNodeMapPrototype::initialize(JS::Realm& realm)
{
    auto& object = *this;
    [[maybe_unused]] auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable;

    object.set_prototype(realm.intrinsics().object_prototype());

    auto length_id = "length"_utf16_fly_string;
    auto native_length_getter = JS::NativeFunction::create(realm, length_getter, 0, length_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_length_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto length_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(length_id, native_length_getter, native_length_setter, length_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    object.define_native_function(realm, "getNamedItemNS"_utf16_fly_string, get_named_item_ns, 2, default_attributes);

    object.define_native_function(realm, "setNamedItem"_utf16_fly_string, set_named_item, 1, default_attributes);

    object.define_native_function(realm, "setNamedItemNS"_utf16_fly_string, set_named_item_ns, 1, default_attributes);

    object.define_native_function(realm, "removeNamedItem"_utf16_fly_string, remove_named_item, 1, default_attributes);

    object.define_native_function(realm, "removeNamedItemNS"_utf16_fly_string, remove_named_item_ns, 2, default_attributes);

    object.define_native_function(realm, "item"_utf16_fly_string, item, 1, default_attributes);
    object.define_native_function(realm, "getNamedItem"_utf16_fly_string, get_named_item, 1, default_attributes);
    object.define_direct_property(vm.well_known_symbol_iterator(), realm.intrinsics().array_prototype()->get_without_side_effects(vm.names.values), JS::Attribute::Configurable | JS::Attribute::Writable);

    object.define_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "NamedNodeMap"_utf16), JS::Attribute::Configurable);
    Base::initialize(realm);
}

void NamedNodeMapPrototype::define_unforgeable_attributes(JS::Realm& realm, [[maybe_unused]] JS::Object& object)
{
    [[maybe_unused]] auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
}

[[maybe_unused]] static JS::ThrowCompletionOr<DOM::NamedNodeMap*> impl_from(JS::VM& vm, JS::Value js_value)
{

    if (auto impl = js_value.as_if<DOM::NamedNodeMap>())
        return impl.ptr();
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "NamedNodeMap");
}

[[maybe_unused]] static JS::ThrowCompletionOr<DOM::NamedNodeMap*> impl_from(JS::VM& vm)
{
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &vm.current_realm()->global_object();
    return impl_from(vm, this_value);
}

JS_DEFINE_NATIVE_FUNCTION(NamedNodeMapPrototype::length_getter)
{
    WebIDL::log_trace(vm, "NamedNodeMapPrototype::length_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->length(); }));

    return JS::Value(static_cast<WebIDL::UnsignedLong>(R));
}

JS_DEFINE_NATIVE_FUNCTION(NamedNodeMapPrototype::get_named_item_ns)
{
    WebIDL::log_trace(vm, "NamedNodeMapPrototype::get_named_item_ns");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::NamedNodeMap* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "getNamedItemNS", "2");

    auto arg0 = vm.argument(0);
    auto namespace_ = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Optional<Utf16FlyString>> {
        Optional<Utf16FlyString> value;

        if (!arg0.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<Utf16FlyString> {
        return TRY(WebIDL::to_utf16_string(vm, arg0));
    }());
        }
        return value;
    }(); }));

    auto arg1 = vm.argument(1);
    auto local_name = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Utf16FlyString> {
        return TRY(WebIDL::to_utf16_string(vm, arg1));
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_named_item_ns(namespace_, local_name); }));
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(NamedNodeMapPrototype::set_named_item)
{
    WebIDL::log_trace(vm, "NamedNodeMapPrototype::set_named_item");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::NamedNodeMap* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "setNamedItem");

    auto arg0 = vm.argument(0);
    auto attr = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ref<DOM::Attr>> {
        if (auto impl = arg0.as_if<DOM::Attr>())
            return *impl;
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Attr");
    }(); }));

    auto original_steps = [&] {
        return throw_dom_exception_if_needed(vm, [&] { return idl_object->set_named_item(attr); });
    };

    [[maybe_unused]] auto R = TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(NamedNodeMapPrototype::set_named_item_ns)
{
    WebIDL::log_trace(vm, "NamedNodeMapPrototype::set_named_item_ns");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::NamedNodeMap* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "setNamedItemNS");

    auto arg0 = vm.argument(0);
    auto attr = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ref<DOM::Attr>> {
        if (auto impl = arg0.as_if<DOM::Attr>())
            return *impl;
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Attr");
    }(); }));

    auto original_steps = [&] {
        return throw_dom_exception_if_needed(vm, [&] { return idl_object->set_named_item_ns(attr); });
    };

    [[maybe_unused]] auto R = TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(NamedNodeMapPrototype::remove_named_item)
{
    WebIDL::log_trace(vm, "NamedNodeMapPrototype::remove_named_item");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::NamedNodeMap* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "removeNamedItem");

    auto arg0 = vm.argument(0);
    auto qualified_name = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Utf16FlyString> {
        return TRY(WebIDL::to_utf16_string(vm, arg0));
    }(); }));

    auto original_steps = [&] {
        return throw_dom_exception_if_needed(vm, [&] { return idl_object->remove_named_item(qualified_name); });
    };

    [[maybe_unused]] auto R = TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(NamedNodeMapPrototype::remove_named_item_ns)
{
    WebIDL::log_trace(vm, "NamedNodeMapPrototype::remove_named_item_ns");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::NamedNodeMap* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "removeNamedItemNS", "2");

    auto arg0 = vm.argument(0);
    auto namespace_ = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Optional<Utf16FlyString>> {
        Optional<Utf16FlyString> value;

        if (!arg0.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<Utf16FlyString> {
        return TRY(WebIDL::to_utf16_string(vm, arg0));
    }());
        }
        return value;
    }(); }));

    auto arg1 = vm.argument(1);
    auto local_name = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Utf16FlyString> {
        return TRY(WebIDL::to_utf16_string(vm, arg1));
    }(); }));

    auto original_steps = [&] {
        return throw_dom_exception_if_needed(vm, [&] { return idl_object->remove_named_item_ns(namespace_, local_name); });
    };

    [[maybe_unused]] auto R = TRY([&]() -> decltype(original_steps()) {
        // For [CEReactions]: https://html.spec.whatwg.org/multipage/custom-elements.html#cereactions

        // 1. Push a new element queue onto this object's relevant agent's custom element reactions stack.
        auto& reactions_stack = HTML::relevant_similar_origin_window_agent(*idl_object).custom_element_reactions_stack;
        reactions_stack.element_queue_stack.append({});

        // 2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.
        auto value_or_exception = original_steps();

        // 3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.
        // 4. Invoke custom element reactions in queue.
        auto queue = reactions_stack.element_queue_stack.take_last();
        Bindings::invoke_custom_element_reactions(queue);

        // 5. If an exception exception was thrown by the original steps, rethrow exception.
        if (value_or_exception.is_error())
            return value_or_exception.release_error();

        // 6. If a value value was returned from the original steps, return value.
        return value_or_exception.release_value();
    }());
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(NamedNodeMapPrototype::item)
{
    WebIDL::log_trace(vm, "NamedNodeMapPrototype::item");
    [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "item");

    auto arg0 = vm.argument(0);
    auto index = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg0, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));



    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->item(index); }));
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(NamedNodeMapPrototype::get_named_item)
{
    WebIDL::log_trace(vm, "NamedNodeMapPrototype::get_named_item");
    [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "getNamedItem");

    auto arg0 = vm.argument(0);
    auto qualified_name = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Utf16FlyString> {
        return TRY(WebIDL::to_utf16_string(vm, arg0));
    }(); }));



    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->get_named_item(qualified_name); }));
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

} // namespace Web::Bindings
