#include <AK/TypeCasts.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Promise.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/WritableStreamDefaultWriter.h>
#include <LibWeb/Streams/WritableStream.h>
#include <LibWeb/Streams/WritableStreamDefaultWriter.h>
#include <LibWeb/WebIDL/Promise.h>
#include <LibWeb/WebIDL/Tracing.h>

namespace Web::Bindings {

void WritableStreamDefaultWriterConstructor::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(1), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "WritableStreamDefaultWriter"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<WritableStreamDefaultWriterPrototype>(realm, "WritableStreamDefaultWriter"_fly_string), 0);
}

JS::ThrowCompletionOr<GC::Ref<JS::Object>> WritableStreamDefaultWriterConstructor::construct([[maybe_unused]] InterfaceConstructor& constructor, [[maybe_unused]] JS::FunctionObject& new_target)
{
    WebIDL::log_trace(constructor.vm(), "WritableStreamDefaultWriterConstructor::construct");
    auto& vm = constructor.vm();
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // To internally create a new object implementing the interface WritableStreamDefaultWriter:

    // 3.2. Let prototype be ? Get(newTarget, "prototype").
    auto prototype = TRY(new_target.get(vm.names.prototype));

    // 3.3. If Type(prototype) is not Object, then:
    if (!prototype.is_object()) {
        // 1. Let targetRealm be ? GetFunctionRealm(newTarget).
        auto* target_realm = TRY(JS::get_function_realm(vm, new_target));

        // 2. Set prototype to the interface prototype object for interface in targetRealm.
        VERIFY(target_realm);
        prototype = &Bindings::ensure_web_prototype<WritableStreamDefaultWriterPrototype>(*target_realm, "WritableStreamDefaultWriter"_fly_string);
    }

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

    auto arg0 = vm.argument(0);
    auto stream = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ref<Streams::WritableStream>> {
        if (auto impl = arg0.as_if<Streams::WritableStream>())
            return *impl;
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "WritableStream");
    }(); }));

    auto impl = TRY(throw_dom_exception_if_needed(vm, [&] { return Streams::WritableStreamDefaultWriter::construct_impl(realm, stream); }));

    // 7. Set instance.[[Prototype]] to prototype.
    VERIFY(prototype.is_object());
    impl->set_prototype(&prototype.as_object());

    // FIXME: Steps 8...11. of the "internally create a new object implementing the interface WritableStreamDefaultWriter" algorithm
    // (https://webidl.spec.whatwg.org/#js-platform-objects) are currently not handled, or are handled within Streams::WritableStreamDefaultWriter::construct_impl().

    return *impl;
}

void WritableStreamDefaultWriterPrototype::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 closed_id = "closed"_utf16_fly_string;
    auto native_closed_getter = JS::NativeFunction::create(realm, closed_getter, 0, closed_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_closed_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto closed_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(closed_id, native_closed_getter, native_closed_setter, closed_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 desired_size_id = "desiredSize"_utf16_fly_string;
    auto native_desired_size_getter = JS::NativeFunction::create(realm, desired_size_getter, 0, desired_size_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_desired_size_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto desired_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(desired_size_id, native_desired_size_getter, native_desired_size_setter, desired_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 ready_id = "ready"_utf16_fly_string;
    auto native_ready_getter = JS::NativeFunction::create(realm, ready_getter, 0, ready_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_ready_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto ready_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(ready_id, native_ready_getter, native_ready_setter, ready_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, "abort"_utf16_fly_string, abort, 0, default_attributes);

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

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

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

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<Streams::WritableStreamDefaultWriter*> 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(WritableStreamDefaultWriterPrototype::closed_getter)
{
    WebIDL::log_trace(vm, "WritableStreamDefaultWriterPrototype::closed_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto steps = [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::Promise>> {
        // 1. Let idlObject be null.
        [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));
        auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->closed(); }));
        return R;
    };

    auto maybe_R = steps();

    // 2. And then, if an exception E was thrown:

    // 1. If attribute’s type is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).
    if (maybe_R.is_throw_completion())
        return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();

    // 2. Otherwise, end these steps and allow the exception to propagate.
    auto R = maybe_R.release_value();

    // 4. Return the result of converting R to a JavaScript value of the type attribute is declared as.
    return GC::Ref { as<JS::Promise>(*R->promise()) };
}

JS_DEFINE_NATIVE_FUNCTION(WritableStreamDefaultWriterPrototype::desired_size_getter)
{
    WebIDL::log_trace(vm, "WritableStreamDefaultWriterPrototype::desired_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->desired_size(); }));

    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R.has_value())
            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.value()));
    }();
}

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

    auto steps = [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::Promise>> {
        // 1. Let idlObject be null.
        [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));
        auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->ready(); }));
        return R;
    };

    auto maybe_R = steps();

    // 2. And then, if an exception E was thrown:

    // 1. If attribute’s type is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).
    if (maybe_R.is_throw_completion())
        return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();

    // 2. Otherwise, end these steps and allow the exception to propagate.
    auto R = maybe_R.release_value();

    // 4. Return the result of converting R to a JavaScript value of the type attribute is declared as.
    return GC::Ref { as<JS::Promise>(*R->promise()) };
}

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

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

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->abort(reason); }));
        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()) };
}

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

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->close(); }));
        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()) };
}

JS_DEFINE_NATIVE_FUNCTION(WritableStreamDefaultWriterPrototype::release_lock)
{
    WebIDL::log_trace(vm, "WritableStreamDefaultWriterPrototype::release_lock");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Streams::WritableStreamDefaultWriter* idl_object = TRY(impl_from(vm));

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

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

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

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->write(chunk); }));
        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()) };
}

} // namespace Web::Bindings
