#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/CryptoKey.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Crypto/CryptoKey.h>
#include <LibWeb/WebIDL/Tracing.h>

namespace Web::Bindings {

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

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

void CryptoKeyPrototype::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 type_id = "type"_utf16_fly_string;
    auto native_type_getter = JS::NativeFunction::create(realm, type_getter, 0, type_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_type_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto type_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(type_id, native_type_getter, native_type_setter, type_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 extractable_id = "extractable"_utf16_fly_string;
    auto native_extractable_getter = JS::NativeFunction::create(realm, extractable_getter, 0, extractable_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_extractable_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto extractable_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(extractable_id, native_extractable_getter, native_extractable_setter, extractable_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 algorithm_id = "algorithm"_utf16_fly_string;
    auto native_algorithm_getter = JS::NativeFunction::create(realm, algorithm_getter, 0, algorithm_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_algorithm_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto algorithm_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(algorithm_id, native_algorithm_getter, native_algorithm_setter, algorithm_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 usages_id = "usages"_utf16_fly_string;
    auto native_usages_getter = JS::NativeFunction::create(realm, usages_getter, 0, usages_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_usages_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto usages_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(usages_id, native_usages_getter, native_usages_setter, usages_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(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "CryptoKey"_utf16), JS::Attribute::Configurable);
}

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<Crypto::CryptoKey*> 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(CryptoKeyPrototype::type_getter)
{
    WebIDL::log_trace(vm, "CryptoKeyPrototype::type_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->type(); }));

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

JS_DEFINE_NATIVE_FUNCTION(CryptoKeyPrototype::extractable_getter)
{
    WebIDL::log_trace(vm, "CryptoKeyPrototype::extractable_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->extractable(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(CryptoKeyPrototype::algorithm_getter)
{
    WebIDL::log_trace(vm, "CryptoKeyPrototype::algorithm_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->algorithm(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(CryptoKeyPrototype::usages_getter)
{
    WebIDL::log_trace(vm, "CryptoKeyPrototype::usages_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->usages(); }));

    return JS::Value(R);
}

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<KeyType> convert_to_idl_value_for_key_type(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 == "public"sv)
        return KeyType::Public;
    if (value_as_string == "private"sv)
        return KeyType::Private;
    if (value_as_string == "secret"sv)
        return KeyType::Secret;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "KeyType");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(KeyType 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 KeyType::Public:
        return "public"_utf16;
    case KeyType::Private:
        return "private"_utf16;
    case KeyType::Secret:
        return "secret"_utf16;
    }
    VERIFY_NOT_REACHED();
}

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<KeyUsage> convert_to_idl_value_for_key_usage(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 == "encrypt"sv)
        return KeyUsage::Encrypt;
    if (value_as_string == "decrypt"sv)
        return KeyUsage::Decrypt;
    if (value_as_string == "sign"sv)
        return KeyUsage::Sign;
    if (value_as_string == "verify"sv)
        return KeyUsage::Verify;
    if (value_as_string == "deriveKey"sv)
        return KeyUsage::Derivekey;
    if (value_as_string == "deriveBits"sv)
        return KeyUsage::Derivebits;
    if (value_as_string == "wrapKey"sv)
        return KeyUsage::Wrapkey;
    if (value_as_string == "unwrapKey"sv)
        return KeyUsage::Unwrapkey;
    if (value_as_string == "encapsulateKey"sv)
        return KeyUsage::Encapsulatekey;
    if (value_as_string == "encapsulateBits"sv)
        return KeyUsage::Encapsulatebits;
    if (value_as_string == "decapsulateKey"sv)
        return KeyUsage::Decapsulatekey;
    if (value_as_string == "decapsulateBits"sv)
        return KeyUsage::Decapsulatebits;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "KeyUsage");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(KeyUsage 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 KeyUsage::Encrypt:
        return "encrypt"_utf16;
    case KeyUsage::Decrypt:
        return "decrypt"_utf16;
    case KeyUsage::Sign:
        return "sign"_utf16;
    case KeyUsage::Verify:
        return "verify"_utf16;
    case KeyUsage::Derivekey:
        return "deriveKey"_utf16;
    case KeyUsage::Derivebits:
        return "deriveBits"_utf16;
    case KeyUsage::Wrapkey:
        return "wrapKey"_utf16;
    case KeyUsage::Unwrapkey:
        return "unwrapKey"_utf16;
    case KeyUsage::Encapsulatekey:
        return "encapsulateKey"_utf16;
    case KeyUsage::Encapsulatebits:
        return "encapsulateBits"_utf16;
    case KeyUsage::Decapsulatekey:
        return "decapsulateKey"_utf16;
    case KeyUsage::Decapsulatebits:
        return "decapsulateBits"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
