#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/PredefinedColorSpace.h>

namespace Web::Bindings {

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<PredefinedColorSpace> convert_to_idl_value_for_predefined_color_space(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 == "srgb"sv)
        return PredefinedColorSpace::Srgb;
    if (value_as_string == "srgb-linear"sv)
        return PredefinedColorSpace::SrgbLinear;
    if (value_as_string == "display-p3"sv)
        return PredefinedColorSpace::DisplayP3;
    if (value_as_string == "display-p3-linear"sv)
        return PredefinedColorSpace::DisplayP3Linear;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "PredefinedColorSpace");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(PredefinedColorSpace 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 PredefinedColorSpace::Srgb:
        return "srgb"_utf16;
    case PredefinedColorSpace::SrgbLinear:
        return "srgb-linear"_utf16;
    case PredefinedColorSpace::DisplayP3:
        return "display-p3"_utf16;
    case PredefinedColorSpace::DisplayP3Linear:
        return "display-p3-linear"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
