#include <AK/Utf16String.h>
#include <AK/Variant.h>
#include <LibGC/ConservativeVector.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Object.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/DocumentType.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/Bindings/Node.h>
#include <LibWeb/Bindings/PlatformObject.h>
#include <LibWeb/DOM/DocumentType.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>

namespace Web::Bindings {

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

    object.set_prototype(&ensure_web_constructor<NodePrototype>(realm, "Node"_fly_string));
    object.define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "DocumentType"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<DocumentTypePrototype>(realm, "DocumentType"_fly_string), 0);
}

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

void DocumentTypePrototype::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(GC::Ref { ensure_web_prototype<NodePrototype>(realm, "Node"_fly_string) });

    auto name_id = "name"_utf16_fly_string;
    auto native_name_getter = JS::NativeFunction::create(realm, name_getter, 0, name_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_name_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto name_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(name_id, native_name_getter, native_name_setter, name_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 public_id_id = "publicId"_utf16_fly_string;
    auto native_public_id_getter = JS::NativeFunction::create(realm, public_id_getter, 0, public_id_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_public_id_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto public_id_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(public_id_id, native_public_id_getter, native_public_id_setter, public_id_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 system_id_id = "systemId"_utf16_fly_string;
    auto native_system_id_getter = JS::NativeFunction::create(realm, system_id_getter, 0, system_id_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_system_id_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto system_id_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(system_id_id, native_system_id_getter, native_system_id_setter, system_id_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, "before"_utf16_fly_string, before, 0, default_attributes);

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

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

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

    auto unscopable_object = JS::Object::create(realm, nullptr);
    MUST(unscopable_object->create_data_property("before"_utf16_fly_string, JS::Value(true)));
    MUST(unscopable_object->create_data_property("after"_utf16_fly_string, JS::Value(true)));
    MUST(unscopable_object->create_data_property("replaceWith"_utf16_fly_string, JS::Value(true)));
    MUST(unscopable_object->create_data_property("remove"_utf16_fly_string, JS::Value(true)));
    object.define_direct_property(vm.well_known_symbol_unscopables(), unscopable_object, JS::Attribute::Configurable);

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<DOM::DocumentType*> 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(DocumentTypePrototype::name_getter)
{
    WebIDL::log_trace(vm, "DocumentTypePrototype::name_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->name(); }));

    return WebIDL::primitive_string_from_string(vm, R);
}

JS_DEFINE_NATIVE_FUNCTION(DocumentTypePrototype::public_id_getter)
{
    WebIDL::log_trace(vm, "DocumentTypePrototype::public_id_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->public_id(); }));

    return WebIDL::primitive_string_from_string(vm, R);
}

JS_DEFINE_NATIVE_FUNCTION(DocumentTypePrototype::system_id_getter)
{
    WebIDL::log_trace(vm, "DocumentTypePrototype::system_id_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->system_id(); }));

    return WebIDL::primitive_string_from_string(vm, R);
}

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

    GC::ConservativeVector<Variant<GC::Ref<DOM::Node>, Utf16String>> nodes;
    if (vm.argument_count() > 0) {
        nodes.ensure_capacity(vm.argument_count() - 0);
        for (size_t i = 0; i < vm.argument_count(); ++i) {
            auto argument = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<DOM::Node>, Utf16String>> {

        if (vm.argument(i).is_object()) {
            [[maybe_unused]] auto& object = vm.argument(i).as_object();

            if (is<PlatformObject>(object)) {

                if (auto* result = as_if<DOM::Node>(object))
                    return Variant<GC::Ref<DOM::Node>, Utf16String> { GC::Ref { *result } };
            }
        }

        auto nodes_string = TRY([&]() -> JS::ThrowCompletionOr<Utf16String> {
        return TRY(WebIDL::to_utf16_string(vm, vm.argument(i)));
    }());
        return Variant<GC::Ref<DOM::Node>, Utf16String> { nodes_string };

        return vm.throw_completion<JS::TypeError>("No union types matched"_utf16);
    }(); }));
            nodes.unchecked_append(move(argument));
        }
    }

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

    [[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::js_undefined();
}

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

    GC::ConservativeVector<Variant<GC::Ref<DOM::Node>, Utf16String>> nodes;
    if (vm.argument_count() > 0) {
        nodes.ensure_capacity(vm.argument_count() - 0);
        for (size_t i = 0; i < vm.argument_count(); ++i) {
            auto argument = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<DOM::Node>, Utf16String>> {

        if (vm.argument(i).is_object()) {
            [[maybe_unused]] auto& object = vm.argument(i).as_object();

            if (is<PlatformObject>(object)) {

                if (auto* result = as_if<DOM::Node>(object))
                    return Variant<GC::Ref<DOM::Node>, Utf16String> { GC::Ref { *result } };
            }
        }

        auto nodes_string = TRY([&]() -> JS::ThrowCompletionOr<Utf16String> {
        return TRY(WebIDL::to_utf16_string(vm, vm.argument(i)));
    }());
        return Variant<GC::Ref<DOM::Node>, Utf16String> { nodes_string };

        return vm.throw_completion<JS::TypeError>("No union types matched"_utf16);
    }(); }));
            nodes.unchecked_append(move(argument));
        }
    }

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

    [[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::js_undefined();
}

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

    GC::ConservativeVector<Variant<GC::Ref<DOM::Node>, Utf16String>> nodes;
    if (vm.argument_count() > 0) {
        nodes.ensure_capacity(vm.argument_count() - 0);
        for (size_t i = 0; i < vm.argument_count(); ++i) {
            auto argument = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<DOM::Node>, Utf16String>> {

        if (vm.argument(i).is_object()) {
            [[maybe_unused]] auto& object = vm.argument(i).as_object();

            if (is<PlatformObject>(object)) {

                if (auto* result = as_if<DOM::Node>(object))
                    return Variant<GC::Ref<DOM::Node>, Utf16String> { GC::Ref { *result } };
            }
        }

        auto nodes_string = TRY([&]() -> JS::ThrowCompletionOr<Utf16String> {
        return TRY(WebIDL::to_utf16_string(vm, vm.argument(i)));
    }());
        return Variant<GC::Ref<DOM::Node>, Utf16String> { nodes_string };

        return vm.throw_completion<JS::TypeError>("No union types matched"_utf16);
    }(); }));
            nodes.unchecked_append(move(argument));
        }
    }

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

    [[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::js_undefined();
}

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

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

    [[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::js_undefined();
}

} // namespace Web::Bindings
