#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/Error.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/Gamepad.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Gamepad/Gamepad.h>
#include <LibWeb/Gamepad/GamepadButton.h>
#include <LibWeb/Gamepad/GamepadHapticActuator.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

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

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

void GamepadPrototype::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 id_id = "id"_utf16_fly_string;
    auto native_id_getter = JS::NativeFunction::create(realm, id_getter, 0, id_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_id_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto 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(id_id, native_id_getter, native_id_setter, 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 index_id = "index"_utf16_fly_string;
    auto native_index_getter = JS::NativeFunction::create(realm, index_getter, 0, index_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_index_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto index_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(index_id, native_index_getter, native_index_setter, index_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 connected_id = "connected"_utf16_fly_string;
    auto native_connected_getter = JS::NativeFunction::create(realm, connected_getter, 0, connected_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_connected_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto connected_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(connected_id, native_connected_getter, native_connected_setter, connected_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 timestamp_id = "timestamp"_utf16_fly_string;
    auto native_timestamp_getter = JS::NativeFunction::create(realm, timestamp_getter, 0, timestamp_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_timestamp_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto timestamp_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(timestamp_id, native_timestamp_getter, native_timestamp_setter, timestamp_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 mapping_id = "mapping"_utf16_fly_string;
    auto native_mapping_getter = JS::NativeFunction::create(realm, mapping_getter, 0, mapping_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_mapping_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto mapping_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(mapping_id, native_mapping_getter, native_mapping_setter, mapping_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 axes_id = "axes"_utf16_fly_string;
    auto native_axes_getter = JS::NativeFunction::create(realm, axes_getter, 0, axes_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_axes_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto axes_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(axes_id, native_axes_getter, native_axes_setter, axes_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 buttons_id = "buttons"_utf16_fly_string;
    auto native_buttons_getter = JS::NativeFunction::create(realm, buttons_getter, 0, buttons_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_buttons_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto buttons_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(buttons_id, native_buttons_getter, native_buttons_setter, buttons_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 vibration_actuator_id = "vibrationActuator"_utf16_fly_string;
    auto native_vibration_actuator_getter = JS::NativeFunction::create(realm, vibration_actuator_getter, 0, vibration_actuator_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_vibration_actuator_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto vibration_actuator_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(vibration_actuator_id, native_vibration_actuator_getter, native_vibration_actuator_setter, vibration_actuator_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_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "Gamepad"_utf16), JS::Attribute::Configurable);
}

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<Gamepad::Gamepad*> 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(GamepadPrototype::id_getter)
{
    WebIDL::log_trace(vm, "GamepadPrototype::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->id(); }));

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

JS_DEFINE_NATIVE_FUNCTION(GamepadPrototype::index_getter)
{
    WebIDL::log_trace(vm, "GamepadPrototype::index_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->index(); }));

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

JS_DEFINE_NATIVE_FUNCTION(GamepadPrototype::connected_getter)
{
    WebIDL::log_trace(vm, "GamepadPrototype::connected_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->connected(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(GamepadPrototype::timestamp_getter)
{
    WebIDL::log_trace(vm, "GamepadPrototype::timestamp_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->timestamp(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(GamepadPrototype::mapping_getter)
{
    WebIDL::log_trace(vm, "GamepadPrototype::mapping_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->mapping(); }));

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

JS_DEFINE_NATIVE_FUNCTION(GamepadPrototype::axes_getter)
{
    WebIDL::log_trace(vm, "GamepadPrototype::axes_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->axes(); }));

    return [&]() -> JS::Value {
        // An IDL sequence<T> value S is converted to a JavaScript value as follows:
        // 1. Let n be the length of S.
        auto sequence_length = R.size();

        // 2. Let A be a new Array object created as if by the expression [].
        auto sequence_array = MUST(JS::Array::create(realm, sequence_length));

        // 3. Initialize i to be 0.
        // 4. While i < n:
        for (size_t sequence_index = 0; sequence_index < sequence_length; ++sequence_index) {
            // 1. Let V be the value in S at index i.
            auto& sequence_element = R.at(sequence_index);

            // 2. Let E be the result of converting V to a JavaScript value.
            JS::Value js_sequence_element = JS::Value(sequence_element);

            // 3. Let P be the result of calling ! ToString(i).
            // 4. Perform ! CreateDataPropertyOrThrow(A, P, E).
            MUST(sequence_array->create_data_property(JS::PropertyKey { sequence_index }, js_sequence_element));

            // 5. Set i to i + 1.
        }

        MUST(sequence_array->set_integrity_level(JS::Object::IntegrityLevel::Frozen));

        // 5. Return A.
        return sequence_array;
    }();
}

JS_DEFINE_NATIVE_FUNCTION(GamepadPrototype::buttons_getter)
{
    WebIDL::log_trace(vm, "GamepadPrototype::buttons_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->buttons(); }));

    return [&]() -> JS::Value {
        // An IDL sequence<T> value S is converted to a JavaScript value as follows:
        // 1. Let n be the length of S.
        auto sequence_length = R.size();

        // 2. Let A be a new Array object created as if by the expression [].
        auto sequence_array = MUST(JS::Array::create(realm, sequence_length));

        // 3. Initialize i to be 0.
        // 4. While i < n:
        for (size_t sequence_index = 0; sequence_index < sequence_length; ++sequence_index) {
            // 1. Let V be the value in S at index i.
            auto& sequence_element = R.at(sequence_index);

            // 2. Let E be the result of converting V to a JavaScript value.
            JS::Value js_sequence_element = JS::Value(sequence_element);

            // 3. Let P be the result of calling ! ToString(i).
            // 4. Perform ! CreateDataPropertyOrThrow(A, P, E).
            MUST(sequence_array->create_data_property(JS::PropertyKey { sequence_index }, js_sequence_element));

            // 5. Set i to i + 1.
        }

        MUST(sequence_array->set_integrity_level(JS::Object::IntegrityLevel::Frozen));

        // 5. Return A.
        return sequence_array;
    }();
}

JS_DEFINE_NATIVE_FUNCTION(GamepadPrototype::vibration_actuator_getter)
{
    WebIDL::log_trace(vm, "GamepadPrototype::vibration_actuator_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->vibration_actuator(); }));

    return JS::Value(R);
}

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<GamepadMappingType> convert_to_idl_value_for_gamepad_mapping_type(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 == ""sv)
        return GamepadMappingType::Empty;
    if (value_as_string == "standard"sv)
        return GamepadMappingType::Standard;
    if (value_as_string == "xr-standard"sv)
        return GamepadMappingType::XrStandard;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "GamepadMappingType");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(GamepadMappingType 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 GamepadMappingType::Empty:
        return ""_utf16;
    case GamepadMappingType::Standard:
        return "standard"_utf16;
    case GamepadMappingType::XrStandard:
        return "xr-standard"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
