#include <AK/TypeCasts.h>
#include <LibGC/Heap.h>
#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/Iterator.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/Promise.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/BaseAudioContext.h>
#include <LibWeb/Bindings/EventTarget.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/PeriodicWave.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/WebAudio/AnalyserNode.h>
#include <LibWeb/WebAudio/AudioBuffer.h>
#include <LibWeb/WebAudio/AudioBufferSourceNode.h>
#include <LibWeb/WebAudio/AudioDestinationNode.h>
#include <LibWeb/WebAudio/AudioListener.h>
#include <LibWeb/WebAudio/BaseAudioContext.h>
#include <LibWeb/WebAudio/BiquadFilterNode.h>
#include <LibWeb/WebAudio/ChannelMergerNode.h>
#include <LibWeb/WebAudio/ChannelSplitterNode.h>
#include <LibWeb/WebAudio/ConstantSourceNode.h>
#include <LibWeb/WebAudio/DelayNode.h>
#include <LibWeb/WebAudio/DynamicsCompressorNode.h>
#include <LibWeb/WebAudio/GainNode.h>
#include <LibWeb/WebAudio/OscillatorNode.h>
#include <LibWeb/WebAudio/PannerNode.h>
#include <LibWeb/WebAudio/PeriodicWave.h>
#include <LibWeb/WebAudio/ScriptProcessorNode.h>
#include <LibWeb/WebAudio/StereoPannerNode.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/WebIDL/Promise.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

void BaseAudioContextConstructor::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<EventTargetPrototype>(realm, "EventTarget"_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, "BaseAudioContext"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<BaseAudioContextPrototype>(realm, "BaseAudioContext"_fly_string), 0);
}

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

void BaseAudioContextPrototype::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<EventTargetPrototype>(realm, "EventTarget"_fly_string) });

    auto destination_id = "destination"_utf16_fly_string;
    auto native_destination_getter = JS::NativeFunction::create(realm, destination_getter, 0, destination_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_destination_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto destination_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(destination_id, native_destination_getter, native_destination_setter, destination_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 sample_rate_id = "sampleRate"_utf16_fly_string;
    auto native_sample_rate_getter = JS::NativeFunction::create(realm, sample_rate_getter, 0, sample_rate_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_sample_rate_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto sample_rate_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(sample_rate_id, native_sample_rate_getter, native_sample_rate_setter, sample_rate_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 current_time_id = "currentTime"_utf16_fly_string;
    auto native_current_time_getter = JS::NativeFunction::create(realm, current_time_getter, 0, current_time_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_current_time_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto current_time_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(current_time_id, native_current_time_getter, native_current_time_setter, current_time_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 listener_id = "listener"_utf16_fly_string;
    auto native_listener_getter = JS::NativeFunction::create(realm, listener_getter, 0, listener_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_listener_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto listener_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(listener_id, native_listener_getter, native_listener_setter, listener_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 state_id = "state"_utf16_fly_string;
    auto native_state_getter = JS::NativeFunction::create(realm, state_getter, 0, state_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_state_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto state_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(state_id, native_state_getter, native_state_setter, state_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 render_quantum_size_id = "renderQuantumSize"_utf16_fly_string;
    auto native_render_quantum_size_getter = JS::NativeFunction::create(realm, render_quantum_size_getter, 0, render_quantum_size_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_render_quantum_size_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto render_quantum_size_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(render_quantum_size_id, native_render_quantum_size_getter, native_render_quantum_size_setter, render_quantum_size_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 onstatechange_id = "onstatechange"_utf16_fly_string;
    auto native_onstatechange_getter = JS::NativeFunction::create(realm, onstatechange_getter, 0, onstatechange_id, &realm, "get"sv);
    auto native_onstatechange_setter = JS::NativeFunction::create(realm, onstatechange_setter, 1, onstatechange_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto onstatechange_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(onstatechange_id, native_onstatechange_getter, native_onstatechange_setter, onstatechange_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, "createAnalyser"_utf16_fly_string, create_analyser, 0, default_attributes);

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

    object.define_native_function(realm, "createBuffer"_utf16_fly_string, create_buffer, 3, default_attributes);

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

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

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

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

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

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

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

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

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

    object.define_native_function(realm, "createPeriodicWave"_utf16_fly_string, create_periodic_wave, 2, default_attributes);

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

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

    object.define_native_function(realm, "decodeAudioData"_utf16_fly_string, decode_audio_data, 1, default_attributes);

    object.define_direct_property("createConvolver"_utf16_fly_string, JS::js_undefined(), default_attributes | JS::Attribute::Unimplemented);

    object.define_direct_property("createIIRFilter"_utf16_fly_string, JS::js_undefined(), default_attributes | JS::Attribute::Unimplemented);

    object.define_direct_property("createWaveShaper"_utf16_fly_string, JS::js_undefined(), default_attributes | JS::Attribute::Unimplemented);

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<WebAudio::BaseAudioContext*> 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(BaseAudioContextPrototype::destination_getter)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::destination_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->destination(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::sample_rate_getter)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::sample_rate_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->sample_rate(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::current_time_getter)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::current_time_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->current_time(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::listener_getter)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::listener_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->listener(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::state_getter)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::state_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->state(); }));

    return JS::PrimitiveString::create(vm, idl_enum_to_string(R));
}

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::render_quantum_size_getter)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::render_quantum_size_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->render_quantum_size(); }));

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::onstatechange_getter)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::onstatechange_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->onstatechange(); }));

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

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

    // 1. Let V be undefined.
    auto V = JS::js_undefined();

    // 2. If any arguments were passed, then set V to the value of the first argument passed.
    if (vm.argument_count() > 0)
        V = vm.argument(0);

    // 3. Let id be attribute’s identifier.

    // 4. Let idlObject be null.
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = nullptr;

    // 5. If attribute is a regular attribute:

    // 1. Let jsValue be the this value, if it is not null or undefined, or realm’s global object otherwise. (This will subsequently cause a TypeError in a few steps, if the global object does not implement target and [LegacyLenientThis] is not specified.)
    auto js_value = vm.this_value();
    if (js_value.is_nullish())
        js_value = &realm.global_object();

    // 2. FIXME: If jsValue is a platform object, then perform a security check, passing jsValue, attribute’s identifier, and "setter".

    // 3. Let validThis be true if jsValue implements target, or false otherwise.
    auto maybe_idl_object = impl_from(vm, js_value);

    // 4. If validThis is false and attribute was not specified with the [LegacyLenientThis] extended attribute, then throw a TypeError.
    idl_object = TRY(maybe_idl_object);

    auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {
        // 6. Let idlValue be determined as follows:
        // -> Otherwise, idlValue is the result of converting V to an IDL value of attribute’s type.
        auto idl_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {
        GC::Ptr<WebIDL::CallbackType> value;
        if (V.is_object()) {

        if (!V.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {

        return vm.heap().allocate<WebIDL::CallbackType>(V.as_object(),  HTML::incumbent_realm(), WebIDL::OperationReturnsPromise::No);
    }());
        }
        }
        return value;
    }(); }));

        // 7. Run the setter steps of attribute with idlObject as this and idlValue as the value.
        auto setter_result = [&]() -> JS::ThrowCompletionOr<void> {
            TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_onstatechange(idl_value); }));
    return {};
        }();

        if (setter_result.is_error())
            return setter_result.release_error();

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY(original_steps());
}

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_analyser)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_analyser");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_biquad_filter)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_biquad_filter");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_buffer)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_buffer");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

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

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

    auto arg2 = vm.argument(2);
    auto sample_rate = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<float> {
        float x = TRY(arg2.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "sampleRate");
        return x;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->create_buffer(number_of_channels, length, sample_rate); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_buffer_source)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_buffer_source");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_channel_merger)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_channel_merger");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_channel_splitter)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_channel_splitter");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_constant_source)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_constant_source");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_delay)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_delay");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    double max_delay_time = 1.0;
    if (!arg0.is_undefined())
        max_delay_time = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<double> {
        auto x = TRY(arg0.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "maxDelayTime");
        return x;
    }(); }));

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_dynamics_compressor)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_dynamics_compressor");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_gain)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_gain");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_oscillator)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_oscillator");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_panner)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_panner");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_periodic_wave)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_periodic_wave");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto real = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Vector<float>> {
        if (!arg0.is_object())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, arg0);

        auto method = TRY(arg0.get_method(vm, vm.well_known_symbol_iterator()));
        if (!method)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, arg0);

        return TRY([&]() -> JS::ThrowCompletionOr<Vector<float>> {
        // To create an IDL value of type sequence<T> given an iterable iterable and an iterator getter method, perform the following steps:
        // 1. Let iteratorRecord be ? GetIteratorFromMethod(iterable, method).
        auto iterator = TRY(JS::get_iterator_from_method(vm, arg0, *method));

        Vector<float> sequence;

        // 2. Initialize i to be 0.
        // 3. Repeat
        for (;;) {
            // 1. Let next be ? IteratorStepValue(iteratorRecord).
            auto next = TRY(JS::iterator_step_value(vm, iterator));

            // 2. If next is done, then return an IDL sequence value of type sequence<T> of length i, where the value of the element at index j is Sj.
            if (!next.has_value())
                break;

            // 3. Initialize Si to the result of converting next to an IDL value of type T.
            auto next_value = next.release_value();
            auto sequence_item = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<float> {
        float x = TRY(next_value.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "real");
        return x;
    }(); }));

            // 4. Set i to i + 1.
            sequence.append(sequence_item);
        }

        return sequence;
    }());
    }(); }));

    auto arg1 = vm.argument(1);
    auto imag = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Vector<float>> {
        if (!arg1.is_object())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, arg1);

        auto method = TRY(arg1.get_method(vm, vm.well_known_symbol_iterator()));
        if (!method)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, arg1);

        return TRY([&]() -> JS::ThrowCompletionOr<Vector<float>> {
        // To create an IDL value of type sequence<T> given an iterable iterable and an iterator getter method, perform the following steps:
        // 1. Let iteratorRecord be ? GetIteratorFromMethod(iterable, method).
        auto iterator = TRY(JS::get_iterator_from_method(vm, arg1, *method));

        Vector<float> sequence;

        // 2. Initialize i to be 0.
        // 3. Repeat
        for (;;) {
            // 1. Let next be ? IteratorStepValue(iteratorRecord).
            auto next = TRY(JS::iterator_step_value(vm, iterator));

            // 2. If next is done, then return an IDL sequence value of type sequence<T> of length i, where the value of the element at index j is Sj.
            if (!next.has_value())
                break;

            // 3. Initialize Si to the result of converting next to an IDL value of type T.
            auto next_value = next.release_value();
            auto sequence_item = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<float> {
        float x = TRY(next_value.to_double(vm));
        if (isinf(x) || isnan(x))
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidRestrictedFloatingPointParameter, "imag");
        return x;
    }(); }));

            // 4. Set i to i + 1.
            sequence.append(sequence_item);
        }

        return sequence;
    }());
    }(); }));

    auto arg2 = vm.argument(2);
    PeriodicWaveConstraints constraints = PeriodicWaveConstraints {};
    if (!arg2.is_undefined())
        constraints = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_periodic_wave_constraints(vm, arg2); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->create_periodic_wave(real, imag, constraints); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_script_processor)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_script_processor");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

    auto arg1 = vm.argument(1);
    WebIDL::UnsignedLong number_of_input_channels = 2;
    if (!arg1.is_undefined())
        number_of_input_channels = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg1, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

    auto arg2 = vm.argument(2);
    WebIDL::UnsignedLong number_of_output_channels = 2;
    if (!arg2.is_undefined())
        number_of_output_channels = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg2, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->create_script_processor(buffer_size, number_of_input_channels, number_of_output_channels); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::create_stereo_panner)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::create_stereo_panner");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

JS_DEFINE_NATIVE_FUNCTION(BaseAudioContextPrototype::decode_audio_data)
{
    WebIDL::log_trace(vm, "BaseAudioContextPrototype::decode_audio_data");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    auto steps = [&realm, &vm]() -> JS::ThrowCompletionOr<GC::Ref<WebIDL::Promise>> {
        (void)realm;
    [[maybe_unused]] WebAudio::BaseAudioContext* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto audio_data = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ref<JS::ArrayBuffer>> {
        // A JavaScript value V is converted to an IDL ArrayBuffer value by running the following algorithm:
        // 1. If V is not an Object, or V does not have an [[ArrayBufferData]] internal slot, then throw a TypeError.
        auto builtin_buffer = arg0.as_if<JS::ArrayBuffer>();
        if (!builtin_buffer)
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "ArrayBuffer");

        // 2. If IsSharedArrayBuffer(V) is true, then throw a TypeError.
        if (builtin_buffer->is_shared_array_buffer())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer);

        // 3. If the conversion is not to an IDL type associated with the [AllowResizable] extended attribute, and
        //    IsFixedLengthArrayBuffer(V) is false, then throw a TypeError.
        if (!builtin_buffer->is_fixed_length())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "fixed-length ArrayBuffer");

        // 4. Return the IDL ArrayBuffer value that is a reference to the same object as V.
        return GC::Ref { *builtin_buffer };
    }(); }));

    auto arg1 = vm.argument(1);
    GC::Ptr<WebIDL::CallbackType> success_callback {};
    if (!arg1.is_undefined())
        success_callback = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {
        GC::Ptr<WebIDL::CallbackType> value;

        if (!arg1.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<WebIDL::CallbackType>> {

        if (!arg1.is_function())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, arg1);

        return vm.heap().allocate<WebIDL::CallbackType>(arg1.as_object(),  HTML::incumbent_realm(), WebIDL::OperationReturnsPromise::No);
    }());
        }
        return value;
    }(); }));

    auto arg2 = vm.argument(2);
    GC::Ptr<WebIDL::CallbackType> error_callback {};
    if (!arg2.is_undefined())
        error_callback = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::CallbackType>> {
        GC::Ptr<WebIDL::CallbackType> value;

        if (!arg2.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<WebIDL::CallbackType>> {

        if (!arg2.is_function())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunction, arg2);

        return vm.heap().allocate<WebIDL::CallbackType>(arg2.as_object(),  HTML::incumbent_realm(), WebIDL::OperationReturnsPromise::No);
    }());
        }
        return value;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->decode_audio_data(audio_data, success_callback, error_callback); }));
        return R;
    };

    auto maybe_R = steps();

    // And then, if an exception E was thrown:
    // 1. If op has a return type that is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).
    // 2. Otherwise, end these steps and allow the exception to propagate.
    if (maybe_R.is_throw_completion())
        return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();

    return GC::Ref { as<JS::Promise>(*maybe_R.release_value()->promise()) };
}

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<AudioContextState> convert_to_idl_value_for_audio_context_state(JS::VM& vm, JS::Value value)
{
    // 1. Let S be the result of calling ? ToString(V).
    auto value_as_string = TRY(value.to_utf16_string(vm));

    // 2. If S is not one of E’s enumeration values, then throw a TypeError.
    // 3. Return the enumeration value of type E that is equal to S.
    if (value_as_string == "suspended"sv)
        return AudioContextState::Suspended;
    if (value_as_string == "running"sv)
        return AudioContextState::Running;
    if (value_as_string == "closed"sv)
        return AudioContextState::Closed;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "AudioContextState");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(AudioContextState value)
{
    // The result of converting an IDL enumeration type value to a JavaScript value is the String value that represents the same sequence of code units as the enumeration value.
    switch (value) {
    case AudioContextState::Suspended:
        return "suspended"_utf16;
    case AudioContextState::Running:
        return "running"_utf16;
    case AudioContextState::Closed:
        return "closed"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
