#include <AK/TypeCasts.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Object.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/QueuingStrategy.h>
#include <LibWeb/Bindings/WritableStream.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 WritableStreamConstructor::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, "WritableStream"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<WritableStreamPrototype>(realm, "WritableStream"_fly_string), 0);
}

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

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

    // 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<WritableStreamPrototype>(*target_realm, "WritableStream"_fly_string);
    }

    auto arg0 = vm.argument(0);
    GC::Ptr<JS::Object> underlying_sink {};
    if (!arg0.is_undefined())
        underlying_sink = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Object>> {
        if (!arg0.is_object())
            return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObject, arg0);
        return GC::Ref { arg0.as_object() };
    }(); }));

    auto arg1 = vm.argument(1);
    QueuingStrategy strategy = QueuingStrategy {};
    if (!arg1.is_undefined())
        strategy = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_queuing_strategy(vm, arg1); }));

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

    // 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 WritableStream" algorithm
    // (https://webidl.spec.whatwg.org/#js-platform-objects) are currently not handled, or are handled within Streams::WritableStream::construct_impl().

    return *impl;
}

void WritableStreamPrototype::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 locked_id = "locked"_utf16_fly_string;
    auto native_locked_getter = JS::NativeFunction::create(realm, locked_getter, 0, locked_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_locked_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto locked_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(locked_id, native_locked_getter, native_locked_setter, locked_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, "getWriter"_utf16_fly_string, get_writer, 0, default_attributes);

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<Streams::WritableStream*> 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(WritableStreamPrototype::locked_getter)
{
    WebIDL::log_trace(vm, "WritableStreamPrototype::locked_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->locked(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(WritableStreamPrototype::abort)
{
    WebIDL::log_trace(vm, "WritableStreamPrototype::abort");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    auto steps = [&realm, &vm]() -> JS::ThrowCompletionOr<GC::Ref<WebIDL::Promise>> {
        (void)realm;
    [[maybe_unused]] Streams::WritableStream* 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(WritableStreamPrototype::close)
{
    WebIDL::log_trace(vm, "WritableStreamPrototype::close");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    auto steps = [&realm, &vm]() -> JS::ThrowCompletionOr<GC::Ref<WebIDL::Promise>> {
        (void)realm;
    [[maybe_unused]] Streams::WritableStream* 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(WritableStreamPrototype::get_writer)
{
    WebIDL::log_trace(vm, "WritableStreamPrototype::get_writer");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Streams::WritableStream* idl_object = TRY(impl_from(vm));

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

} // namespace Web::Bindings
