#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Object.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/MediaDeviceInfo.h>
#include <LibWeb/MediaCapture/MediaDeviceInfo.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>

namespace Web::Bindings {

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

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

void MediaDeviceInfoPrototype::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 device_id_id = "deviceId"_utf16_fly_string;
    auto native_device_id_getter = JS::NativeFunction::create(realm, device_id_getter, 0, device_id_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_device_id_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto device_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(device_id_id, native_device_id_getter, native_device_id_setter, device_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 kind_id = "kind"_utf16_fly_string;
    auto native_kind_getter = JS::NativeFunction::create(realm, kind_getter, 0, kind_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_kind_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto kind_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(kind_id, native_kind_getter, native_kind_setter, kind_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 label_id = "label"_utf16_fly_string;
    auto native_label_getter = JS::NativeFunction::create(realm, label_getter, 0, label_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_label_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto label_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(label_id, native_label_getter, native_label_setter, label_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 group_id_id = "groupId"_utf16_fly_string;
    auto native_group_id_getter = JS::NativeFunction::create(realm, group_id_getter, 0, group_id_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_group_id_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto group_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(group_id_id, native_group_id_getter, native_group_id_setter, group_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, "toJSON"_utf16_fly_string, to_json, 0, default_attributes);

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<MediaCapture::MediaDeviceInfo*> 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(MediaDeviceInfoPrototype::device_id_getter)
{
    WebIDL::log_trace(vm, "MediaDeviceInfoPrototype::device_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->device_id(); }));

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

JS_DEFINE_NATIVE_FUNCTION(MediaDeviceInfoPrototype::kind_getter)
{
    WebIDL::log_trace(vm, "MediaDeviceInfoPrototype::kind_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->kind(); }));

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

JS_DEFINE_NATIVE_FUNCTION(MediaDeviceInfoPrototype::label_getter)
{
    WebIDL::log_trace(vm, "MediaDeviceInfoPrototype::label_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->label(); }));

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

JS_DEFINE_NATIVE_FUNCTION(MediaDeviceInfoPrototype::group_id_getter)
{
    WebIDL::log_trace(vm, "MediaDeviceInfoPrototype::group_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->group_id(); }));

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

JS_DEFINE_NATIVE_FUNCTION(MediaDeviceInfoPrototype::to_json)
{
    WebIDL::log_trace(vm, "MediaDeviceInfoPrototype::to_json");
    auto& realm = *vm.current_realm();

    [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));

    // 4. Let result be OrdinaryObjectCreate(%Object.prototype%).
    auto result = JS::Object::create(realm, realm.intrinsics().object_prototype());

    // 5. For each key → value of map:
    auto device_id_0_value = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->device_id(); }));

    // 1. Let k be key converted to a JavaScript value.
    auto device_id_0_key = "deviceId"_utf16_fly_string;

    // 2. Let v be value converted to a JavaScript value.
    auto device_id_0_value_js = WebIDL::primitive_string_from_string(vm, device_id_0_value);

    // 3. Perform ! CreateDataPropertyOrThrow(result, k, v).
    MUST(result->create_data_property(device_id_0_key, device_id_0_value_js));
    auto kind_1_value = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->kind(); }));

    // 1. Let k be key converted to a JavaScript value.
    auto kind_1_key = "kind"_utf16_fly_string;

    // 2. Let v be value converted to a JavaScript value.
    auto kind_1_value_js = JS::PrimitiveString::create(vm, idl_enum_to_string(kind_1_value));

    // 3. Perform ! CreateDataPropertyOrThrow(result, k, v).
    MUST(result->create_data_property(kind_1_key, kind_1_value_js));
    auto label_2_value = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->label(); }));

    // 1. Let k be key converted to a JavaScript value.
    auto label_2_key = "label"_utf16_fly_string;

    // 2. Let v be value converted to a JavaScript value.
    auto label_2_value_js = WebIDL::primitive_string_from_string(vm, label_2_value);

    // 3. Perform ! CreateDataPropertyOrThrow(result, k, v).
    MUST(result->create_data_property(label_2_key, label_2_value_js));
    auto group_id_3_value = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->group_id(); }));

    // 1. Let k be key converted to a JavaScript value.
    auto group_id_3_key = "groupId"_utf16_fly_string;

    // 2. Let v be value converted to a JavaScript value.
    auto group_id_3_value_js = WebIDL::primitive_string_from_string(vm, group_id_3_value);

    // 3. Perform ! CreateDataPropertyOrThrow(result, k, v).
    MUST(result->create_data_property(group_id_3_key, group_id_3_value_js));

    // 6. Return result.
    return result;
}

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<MediaDeviceKind> convert_to_idl_value_for_media_device_kind(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 == "audioinput"sv)
        return MediaDeviceKind::Audioinput;
    if (value_as_string == "audiooutput"sv)
        return MediaDeviceKind::Audiooutput;
    if (value_as_string == "videoinput"sv)
        return MediaDeviceKind::Videoinput;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "MediaDeviceKind");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(MediaDeviceKind 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 MediaDeviceKind::Audioinput:
        return "audioinput"_utf16;
    case MediaDeviceKind::Audiooutput:
        return "audiooutput"_utf16;
    case MediaDeviceKind::Videoinput:
        return "videoinput"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
