#include <AK/String.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/IDBCursor.h>
#include <LibWeb/Bindings/IDBIndex.h>
#include <LibWeb/Bindings/IDBObjectStore.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/IndexedDB/IDBIndex.h>
#include <LibWeb/IndexedDB/IDBObjectStore.h>
#include <LibWeb/IndexedDB/IDBRequest.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

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

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

void IDBIndexPrototype::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 name_id = "name"_utf16_fly_string;
    auto native_name_getter = JS::NativeFunction::create(realm, name_getter, 0, name_id, &realm, "get"sv);
    auto native_name_setter = JS::NativeFunction::create(realm, name_setter, 1, name_id, &realm, "set"sv);

    // 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 object_store_id = "objectStore"_utf16_fly_string;
    auto native_object_store_getter = JS::NativeFunction::create(realm, object_store_getter, 0, object_store_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_object_store_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto object_store_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(object_store_id, native_object_store_getter, native_object_store_setter, object_store_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 key_path_id = "keyPath"_utf16_fly_string;
    auto native_key_path_getter = JS::NativeFunction::create(realm, key_path_getter, 0, key_path_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_key_path_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto key_path_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(key_path_id, native_key_path_getter, native_key_path_setter, key_path_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 multi_entry_id = "multiEntry"_utf16_fly_string;
    auto native_multi_entry_getter = JS::NativeFunction::create(realm, multi_entry_getter, 0, multi_entry_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_multi_entry_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto multi_entry_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(multi_entry_id, native_multi_entry_getter, native_multi_entry_setter, multi_entry_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 unique_id = "unique"_utf16_fly_string;
    auto native_unique_getter = JS::NativeFunction::create(realm, unique_getter, 0, unique_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_unique_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto unique_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(unique_id, native_unique_getter, native_unique_setter, unique_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, "get"_utf16_fly_string, get, 1, default_attributes);

    object.define_native_function(realm, "getKey"_utf16_fly_string, get_key, 1, default_attributes);

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

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

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

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

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

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

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<IndexedDB::IDBIndex*> 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(IDBIndexPrototype::name_getter)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::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(IDBIndexPrototype::object_store_getter)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::object_store_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->object_store(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBIndexPrototype::key_path_getter)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::key_path_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->key_path(); }));

    return R;
}

JS_DEFINE_NATIVE_FUNCTION(IDBIndexPrototype::multi_entry_getter)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::multi_entry_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->multi_entry(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBIndexPrototype::unique_getter)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::unique_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->unique(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(IDBIndexPrototype::name_setter)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::name_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]] IndexedDB::IDBIndex* 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<String> {
        return TRY(WebIDL::to_string(vm, V));
    }(); }));

        // 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_name(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(IDBIndexPrototype::get)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::get");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBIndex* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

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

JS_DEFINE_NATIVE_FUNCTION(IDBIndexPrototype::get_key)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::get_key");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBIndex* idl_object = TRY(impl_from(vm));

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

    auto arg0 = vm.argument(0);
    auto query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

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

JS_DEFINE_NATIVE_FUNCTION(IDBIndexPrototype::get_all)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::get_all");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBIndex* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    Optional<JS::Value> query {};
    if (!arg0.is_undefined())
        query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

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

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

JS_DEFINE_NATIVE_FUNCTION(IDBIndexPrototype::get_all_keys)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::get_all_keys");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBIndex* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    Optional<JS::Value> query {};
    if (!arg0.is_undefined())
        query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

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

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

JS_DEFINE_NATIVE_FUNCTION(IDBIndexPrototype::get_all_records)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::get_all_records");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBIndex* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    IDBGetAllOptions options = IDBGetAllOptions {};
    if (!arg0.is_undefined())
        options = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_idb_get_all_options(vm, arg0); }));

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

JS_DEFINE_NATIVE_FUNCTION(IDBIndexPrototype::count)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::count");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBIndex* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    Optional<JS::Value> query {};
    if (!arg0.is_undefined())
        query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

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

JS_DEFINE_NATIVE_FUNCTION(IDBIndexPrototype::open_cursor)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::open_cursor");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBIndex* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    Optional<JS::Value> query {};
    if (!arg0.is_undefined())
        query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    auto arg1 = vm.argument(1);
    IDBCursorDirection direction = IDBCursorDirection::Next;
    if (!arg1.is_undefined())
        direction = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_idb_cursor_direction(vm, arg1); }));

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

JS_DEFINE_NATIVE_FUNCTION(IDBIndexPrototype::open_key_cursor)
{
    WebIDL::log_trace(vm, "IDBIndexPrototype::open_key_cursor");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] IndexedDB::IDBIndex* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    Optional<JS::Value> query {};
    if (!arg0.is_undefined())
        query = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    auto arg1 = vm.argument(1);
    IDBCursorDirection direction = IDBCursorDirection::Next;
    if (!arg1.is_undefined())
        direction = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_idb_cursor_direction(vm, arg1); }));

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

} // namespace Web::Bindings
