#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/NodeIterator.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/DOM/NodeFilter.h>
#include <LibWeb/DOM/NodeIterator.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

void NodeIteratorConstructor::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, "NodeIterator"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<NodeIteratorPrototype>(realm, "NodeIterator"_fly_string), 0);
}

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

void NodeIteratorPrototype::initialize(JS::Realm& realm, JS::Object& object)
{
    [[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 root_id = "root"_utf16_fly_string;
    auto native_root_getter = JS::NativeFunction::create(realm, root_getter, 0, root_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_root_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto root_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(root_id, native_root_getter, native_root_setter, root_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.
    auto reference_node_id = "referenceNode"_utf16_fly_string;
    auto native_reference_node_getter = JS::NativeFunction::create(realm, reference_node_getter, 0, reference_node_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_reference_node_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto reference_node_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(reference_node_id, native_reference_node_getter, native_reference_node_setter, reference_node_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.
    auto pointer_before_reference_node_id = "pointerBeforeReferenceNode"_utf16_fly_string;
    auto native_pointer_before_reference_node_getter = JS::NativeFunction::create(realm, pointer_before_reference_node_getter, 0, pointer_before_reference_node_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_pointer_before_reference_node_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto pointer_before_reference_node_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(pointer_before_reference_node_id, native_pointer_before_reference_node_getter, native_pointer_before_reference_node_setter, pointer_before_reference_node_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.
    auto what_to_show_id = "whatToShow"_utf16_fly_string;
    auto native_what_to_show_getter = JS::NativeFunction::create(realm, what_to_show_getter, 0, what_to_show_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_what_to_show_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto what_to_show_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(what_to_show_id, native_what_to_show_getter, native_what_to_show_setter, what_to_show_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.
    auto filter_id = "filter"_utf16_fly_string;
    auto native_filter_getter = JS::NativeFunction::create(realm, filter_getter, 0, filter_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_filter_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto filter_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(filter_id, native_filter_getter, native_filter_setter, filter_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, "nextNode"_utf16_fly_string, next_node, 0, default_attributes);

    object.define_native_function(realm, "previousNode"_utf16_fly_string, previous_node, 0, default_attributes);

    object.define_native_function(realm, "detach"_utf16_fly_string, detach, 0, default_attributes);

    object.define_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "NodeIterator"_utf16), JS::Attribute::Configurable);
}

void NodeIteratorPrototype::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::NodeIterator*> impl_from(JS::VM& vm, JS::Value js_value)
{

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

[[maybe_unused]] static JS::ThrowCompletionOr<DOM::NodeIterator*> 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(NodeIteratorPrototype::root_getter)
{
    WebIDL::log_trace(vm, "NodeIteratorPrototype::root_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->root(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(NodeIteratorPrototype::reference_node_getter)
{
    WebIDL::log_trace(vm, "NodeIteratorPrototype::reference_node_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->reference_node(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(NodeIteratorPrototype::pointer_before_reference_node_getter)
{
    WebIDL::log_trace(vm, "NodeIteratorPrototype::pointer_before_reference_node_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->pointer_before_reference_node(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(NodeIteratorPrototype::what_to_show_getter)
{
    WebIDL::log_trace(vm, "NodeIteratorPrototype::what_to_show_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->what_to_show(); }));

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

JS_DEFINE_NATIVE_FUNCTION(NodeIteratorPrototype::filter_getter)
{
    WebIDL::log_trace(vm, "NodeIteratorPrototype::filter_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->filter(); }));

    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(R->callback().callback);
    }();
}

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

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->next_node(); }));
    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(NodeIteratorPrototype::previous_node)
{
    WebIDL::log_trace(vm, "NodeIteratorPrototype::previous_node");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::NodeIterator* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->previous_node(); }));
    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(NodeIteratorPrototype::detach)
{
    WebIDL::log_trace(vm, "NodeIteratorPrototype::detach");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::NodeIterator* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->detach(); }));
    return JS::js_undefined();
}

} // namespace Web::Bindings
