#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Object.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/DOMMatrixReadOnly.h>
#include <LibWeb/Bindings/DOMPointReadOnly.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Geometry/DOMPoint.h>
#include <LibWeb/Geometry/DOMPointReadOnly.h>
#include <LibWeb/WebIDL/Tracing.h>

namespace Web::Bindings {

void DOMPointReadOnlyConstructor::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, "DOMPointReadOnly"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<DOMPointReadOnlyPrototype>(realm, "DOMPointReadOnly"_fly_string), 0);
    object.define_native_function(realm, "fromPoint"_utf16_fly_string, from_point, 0, JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable);

}

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

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

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

    auto arg0 = vm.argument(0);
    double x = 0;
    if (!arg0.is_undefined())
        x = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0.to_double(vm); }));

    auto arg1 = vm.argument(1);
    double y = 0;
    if (!arg1.is_undefined())
        y = TRY(throw_dom_exception_if_needed(vm, [&] { return arg1.to_double(vm); }));

    auto arg2 = vm.argument(2);
    double z = 0;
    if (!arg2.is_undefined())
        z = TRY(throw_dom_exception_if_needed(vm, [&] { return arg2.to_double(vm); }));

    auto arg3 = vm.argument(3);
    double w = 1;
    if (!arg3.is_undefined())
        w = TRY(throw_dom_exception_if_needed(vm, [&] { return arg3.to_double(vm); }));

    auto impl = TRY(throw_dom_exception_if_needed(vm, [&] { return Geometry::DOMPointReadOnly::construct_impl(realm, x, y, z, w); }));

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

    return *impl;
}

void DOMPointReadOnlyPrototype::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 x_id = "x"_utf16_fly_string;
    auto native_x_getter = JS::NativeFunction::create(realm, x_getter, 0, x_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_x_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto x_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(x_id, native_x_getter, native_x_setter, x_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 y_id = "y"_utf16_fly_string;
    auto native_y_getter = JS::NativeFunction::create(realm, y_getter, 0, y_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_y_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto y_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(y_id, native_y_getter, native_y_setter, y_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 z_id = "z"_utf16_fly_string;
    auto native_z_getter = JS::NativeFunction::create(realm, z_getter, 0, z_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_z_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto z_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(z_id, native_z_getter, native_z_setter, z_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 w_id = "w"_utf16_fly_string;
    auto native_w_getter = JS::NativeFunction::create(realm, w_getter, 0, w_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_w_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto w_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(w_id, native_w_getter, native_w_setter, w_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, "matrixTransform"_utf16_fly_string, matrix_transform, 0, default_attributes);

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

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<Geometry::DOMPointReadOnly*> 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(DOMPointReadOnlyConstructor::from_point)
{
    WebIDL::log_trace(vm, "DOMPointReadOnlyConstructor::from_point");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    auto arg0 = vm.argument(0);
    DOMPointInit other = DOMPointInit {};
    if (!arg0.is_undefined())
        other = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_dom_point_init(vm, arg0); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return Geometry::DOMPointReadOnly::from_point(vm, other); }));
    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(DOMPointReadOnlyPrototype::x_getter)
{
    WebIDL::log_trace(vm, "DOMPointReadOnlyPrototype::x_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->x(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(DOMPointReadOnlyPrototype::y_getter)
{
    WebIDL::log_trace(vm, "DOMPointReadOnlyPrototype::y_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->y(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(DOMPointReadOnlyPrototype::z_getter)
{
    WebIDL::log_trace(vm, "DOMPointReadOnlyPrototype::z_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->z(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(DOMPointReadOnlyPrototype::w_getter)
{
    WebIDL::log_trace(vm, "DOMPointReadOnlyPrototype::w_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->w(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(DOMPointReadOnlyPrototype::matrix_transform)
{
    WebIDL::log_trace(vm, "DOMPointReadOnlyPrototype::matrix_transform");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] Geometry::DOMPointReadOnly* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    DOMMatrixInit matrix = DOMMatrixInit {};
    if (!arg0.is_undefined())
        matrix = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_dom_matrix_init(vm, arg0); }));

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

JS_DEFINE_NATIVE_FUNCTION(DOMPointReadOnlyPrototype::to_json)
{
    WebIDL::log_trace(vm, "DOMPointReadOnlyPrototype::to_json");
    auto& realm = *vm.current_realm();

    [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));

    // 4. Let result be OrdinaryObjectCreate(%Object.prototype%).
    auto result = JS::Object::create(realm, realm.intrinsics().object_prototype());

    // 5. For each key → value of map:
    auto x_0_value = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->x(); }));

    // 1. Let k be key converted to a JavaScript value.
    auto x_0_key = "x"_utf16_fly_string;

    // 2. Let v be value converted to a JavaScript value.
    auto x_0_value_js = JS::Value(x_0_value);

    // 3. Perform ! CreateDataPropertyOrThrow(result, k, v).
    MUST(result->create_data_property(x_0_key, x_0_value_js));
    auto y_1_value = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->y(); }));

    // 1. Let k be key converted to a JavaScript value.
    auto y_1_key = "y"_utf16_fly_string;

    // 2. Let v be value converted to a JavaScript value.
    auto y_1_value_js = JS::Value(y_1_value);

    // 3. Perform ! CreateDataPropertyOrThrow(result, k, v).
    MUST(result->create_data_property(y_1_key, y_1_value_js));
    auto z_2_value = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->z(); }));

    // 1. Let k be key converted to a JavaScript value.
    auto z_2_key = "z"_utf16_fly_string;

    // 2. Let v be value converted to a JavaScript value.
    auto z_2_value_js = JS::Value(z_2_value);

    // 3. Perform ! CreateDataPropertyOrThrow(result, k, v).
    MUST(result->create_data_property(z_2_key, z_2_value_js));
    auto w_3_value = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->w(); }));

    // 1. Let k be key converted to a JavaScript value.
    auto w_3_key = "w"_utf16_fly_string;

    // 2. Let v be value converted to a JavaScript value.
    auto w_3_value_js = JS::Value(w_3_value);

    // 3. Perform ! CreateDataPropertyOrThrow(result, k, v).
    MUST(result->create_data_property(w_3_key, w_3_value_js));

    // 6. Return result.
    return result;
}

// https://webidl.spec.whatwg.org/#es-dictionary
JS::ThrowCompletionOr<DOMPointInit> convert_to_idl_value_for_dom_point_init(JS::VM& vm, JS::Value js_dict)
{
    // 1. If jsDict is not an Object and jsDict is neither undefined nor null, then throw a TypeError.
    if (!js_dict.is_object() && !js_dict.is_nullish())
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "DOMPointInit");

    // 2. Let idlDict be an empty ordered map, representing a dictionary of type D.
    // 3. Let dictionaries be a list consisting of D and all of D’s inherited dictionaries, in order from least to most derived.
    // 4. For each dictionary dictionary in dictionaries, in order:
    // NB: We defer construction until the return initializer because some members may not be default-constructible. Inherited dictionaries are represented by the generated C++ struct inheritance.

    // 5. Return idlDict.
    return DOMPointInit {
        .w = TRY([&]() -> JS::ThrowCompletionOr<double> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("w"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value.to_double(vm); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = 1;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        .x = TRY([&]() -> JS::ThrowCompletionOr<double> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("x"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value.to_double(vm); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = 0;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        .y = TRY([&]() -> JS::ThrowCompletionOr<double> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("y"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value.to_double(vm); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = 0;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        .z = TRY([&]() -> JS::ThrowCompletionOr<double> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("z"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value.to_double(vm); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = 0;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
    };
}

} // namespace Web::Bindings
