#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/EventTarget.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/ServiceWorkerRegistration.h>
#include <LibWeb/ServiceWorker/ServiceWorker.h>
#include <LibWeb/ServiceWorker/ServiceWorkerRegistration.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>

namespace Web::Bindings {

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

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

void ServiceWorkerRegistrationPrototype::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 installing_id = "installing"_utf16_fly_string;
    auto native_installing_getter = JS::NativeFunction::create(realm, installing_getter, 0, installing_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_installing_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto installing_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(installing_id, native_installing_getter, native_installing_setter, installing_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 waiting_id = "waiting"_utf16_fly_string;
    auto native_waiting_getter = JS::NativeFunction::create(realm, waiting_getter, 0, waiting_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_waiting_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto waiting_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(waiting_id, native_waiting_getter, native_waiting_setter, waiting_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 active_id = "active"_utf16_fly_string;
    auto native_active_getter = JS::NativeFunction::create(realm, active_getter, 0, active_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_active_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto active_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(active_id, native_active_getter, native_active_setter, active_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 scope_id = "scope"_utf16_fly_string;
    auto native_scope_getter = JS::NativeFunction::create(realm, scope_getter, 0, scope_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_scope_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto scope_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(scope_id, native_scope_getter, native_scope_setter, scope_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 update_via_cache_id = "updateViaCache"_utf16_fly_string;
    auto native_update_via_cache_getter = JS::NativeFunction::create(realm, update_via_cache_getter, 0, update_via_cache_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_update_via_cache_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto update_via_cache_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(update_via_cache_id, native_update_via_cache_getter, native_update_via_cache_setter, update_via_cache_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("update"_utf16_fly_string, JS::js_undefined(), default_attributes | JS::Attribute::Unimplemented);

    object.define_direct_property("unregister"_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, "ServiceWorkerRegistration"_utf16), JS::Attribute::Configurable);
}

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<ServiceWorker::ServiceWorkerRegistration*> 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(ServiceWorkerRegistrationPrototype::installing_getter)
{
    WebIDL::log_trace(vm, "ServiceWorkerRegistrationPrototype::installing_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->installing(); }));

    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(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(ServiceWorkerRegistrationPrototype::waiting_getter)
{
    WebIDL::log_trace(vm, "ServiceWorkerRegistrationPrototype::waiting_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->waiting(); }));

    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(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(ServiceWorkerRegistrationPrototype::active_getter)
{
    WebIDL::log_trace(vm, "ServiceWorkerRegistrationPrototype::active_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->active(); }));

    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(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(ServiceWorkerRegistrationPrototype::scope_getter)
{
    WebIDL::log_trace(vm, "ServiceWorkerRegistrationPrototype::scope_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->scope(); }));

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

JS_DEFINE_NATIVE_FUNCTION(ServiceWorkerRegistrationPrototype::update_via_cache_getter)
{
    WebIDL::log_trace(vm, "ServiceWorkerRegistrationPrototype::update_via_cache_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->update_via_cache(); }));

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

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<ServiceWorkerUpdateViaCache> convert_to_idl_value_for_service_worker_update_via_cache(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 == "imports"sv)
        return ServiceWorkerUpdateViaCache::Imports;
    if (value_as_string == "all"sv)
        return ServiceWorkerUpdateViaCache::All;
    if (value_as_string == "none"sv)
        return ServiceWorkerUpdateViaCache::None;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "ServiceWorkerUpdateViaCache");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(ServiceWorkerUpdateViaCache 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 ServiceWorkerUpdateViaCache::Imports:
        return "imports"_utf16;
    case ServiceWorkerUpdateViaCache::All:
        return "all"_utf16;
    case ServiceWorkerUpdateViaCache::None:
        return "none"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
