/*

Copyright (C) 2016 Apple Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1.  Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
2.  Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#pragma once

#include "JSDOMBinding.h"
#include "JSDOMPromise.h"
#include "CompositeOperation.h"
#include "CompositeOperationOrAuto.h"
#include "FetchOptions.h"
#include "FillMode.h"
#include "FontFaceLoadStatus.h"
#include "FontFaceSetLoadStatus.h"
#include "ImageBitmapOptions.h"
#include "IterationCompositeOperation.h"
#include "MediaDeviceInfo.h"
#include "MediaKeyMessageType.h"
#include "MediaKeySessionType.h"
#include "MediaKeyStatus.h"
#include "MediaKeysRequirement.h"
#include "MediaStreamTrackState.h"
#include "PlaybackDirection.h"
#include "PredefinedColorSpace.h"
#include "ResourceResponseBase.h"
#include "RTCBundlePolicy.h"
#include "RTCDataChannelState.h"
#include "RTCIceConnectionState.h"
#include "RTCIceGatheringState.h"
#include "RTCIceTransportPolicy.h"
#include "RTCPeerConnectionState.h"
#include "RTCRtpParameters.h"
#include "RTCRtpTransceiverDirection.h"
#include "RTCSignalingState.h"
#include "RTCSdpType.h"
#include "RTCStatsType.h"
#include "ScriptValue.h"
#include "ShadowRootMode.h"
#include "SourceBufferAppendMode.h"
#include "AnimationPlayState.h"
#include "AnimationReplaceState.h"
#include "XMLHttpRequest.h"
#include <wtf/Optional.h>

namespace WebCore {

template<typename T> typename Converter<T>::OptionalValue convertOptional(JSC::ExecState&, JSC::JSValue);
template<typename T, typename U> T convertOptional(JSC::ExecState&, JSC::JSValue, U& defaultValue);

// This is where the implementation of the things declared above begins:

template<typename T> T convert(JSC::ExecState& state, JSC::JSValue value)
{
    return Converter<T>::convert(state, value);
}

template<typename T> T convert(JSC::ExecState& state, JSC::JSValue value, IntegerConversionConfiguration configuration)
{
    return Converter<T>::convert(state, value, configuration);
}

template<typename T> inline T convert(JSC::ExecState& state, JSC::JSValue value, ShouldAllowNonFinite allow)
{
    //static_assert(std::is_same<T, float>::value || std::is_same<T, double>::value, "ShouldAllowNonFinite can only be used with float or double");
    double number = value.toNumber(&state);
    if (allow == ShouldAllowNonFiniteNo && UNLIKELY(!std::isfinite(number)))
        throwNonFiniteTypeError(state);
    return static_cast<T>(number);
}

template<typename T> typename Converter<T>::OptionalValue inline convertOptional(JSC::ExecState& state, JSC::JSValue value)
{
    return value.isUndefined() ? typename Converter<T>::OptionalValue() : convert<T>(state, value);
}

template<typename T, typename U> inline T convertOptional(JSC::ExecState& state, JSC::JSValue value, U& defaultValue)
{
    return value.isUndefined() ? defaultValue : convert<T>(state, value);
}

template<typename T, typename JST> inline T* convertWrapperType(JSC::ExecState& state, JSC::JSValue value, IsNullable isNullable)
{
    T* object = JST::toWrapped(value);
    if (!object && (isNullable == IsNullableNo || !value.isUndefinedOrNull()))
        throwTypeError(&state, state.vm());
    return object;
}

template<typename T, typename JST, typename VectorType> inline VectorType convertWrapperTypeSequence(JSC::ExecState& state, JSC::JSValue value)
{
    return toRefPtrNativeArray<T, JST, VectorType>(state, value);
}

template<typename T> struct DefaultConverter {
    typedef Optional<T> OptionalValue;
};

template<typename T> struct Converter : DefaultConverter<T> {
};

template<> struct Converter<JSC::JSValue> : DefaultConverter<ScriptValue> {
    static ALWAYS_INLINE JSC::JSValue convert(JSC::ExecState& state, JSC::JSValue value)
    {
        return value;
    }
};

template<> struct Converter<bool> : DefaultConverter<bool> {
	static ALWAYS_INLINE bool convert(JSC::ExecState& state, JSC::JSValue value)
    {
        return value.toBoolean(&state);
    }
};

template<> struct Converter<String> : DefaultConverter<String> {
    typedef String OptionalValue; // Use null string to mean an optional value was not present.
    static ALWAYS_INLINE String convert(JSC::ExecState& state, JSC::JSValue value)
    {
        return value.toWTFString(&state);
    }
};

template<> struct Converter<double> : DefaultConverter<double> {
    static ALWAYS_INLINE double convert(JSC::ExecState& state, JSC::JSValue value)
    {
        return value.toNumber(&state);
    }
};

template<> struct Converter<ScriptValue> : DefaultConverter<ScriptValue> {
    static ScriptValue convert(JSC::ExecState& state, JSC::JSValue value)
    {
        return ScriptValue(state.vm(), value);
    }
};

template<> struct Converter<RefPtr<DOMPromise>> : DefaultConverter<RefPtr<DOMPromise>> {
    static RefPtr<DOMPromise> convert(JSC::ExecState& state, JSC::JSValue value)
    {
        JSC::VM& vm = state.vm();
        //auto scope = DECLARE_THROW_SCOPE(vm);
        auto* globalObject = JSC::jsDynamicCast<JSDOMGlobalObject*>(state.lexicalGlobalObject());
        if (!globalObject)
            return nullptr;

        // 1. Let resolve be the original value of %Promise%.resolve.
        // 2. Let promise be the result of calling resolve with %Promise% as the this value and V as the single argument value.
        auto* promise = JSC::JSPromise::resolve(*globalObject, value);
        if (vm.exception()) {
            //exceptionThrower(state, scope);
            return nullptr;
        }
        ASSERT(promise);

        // 3. Return the IDL promise type value that is a reference to the same object as promise.
        return DOMPromise::create(*globalObject, *promise);
    }
};

template<> struct Converter<FillMode> : DefaultConverter<FillMode> {
    static FillMode convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<ShadowRootMode> : DefaultConverter<ShadowRootMode> {
    static ShadowRootMode convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<PlaybackDirection> : DefaultConverter<PlaybackDirection> {
    static PlaybackDirection convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<CompositeOperation> : DefaultConverter<CompositeOperation> {
    static CompositeOperation convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<CompositeOperationOrAuto> : DefaultConverter<CompositeOperationOrAuto> {
    static CompositeOperationOrAuto convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<IterationCompositeOperation> : DefaultConverter<IterationCompositeOperation> {
    static IterationCompositeOperation convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<XMLHttpRequest::ResponseType> : DefaultConverter<XMLHttpRequest::ResponseType> {
    static XMLHttpRequest::ResponseType convert(JSC::ExecState& state, JSC::JSValue value);
};

#if ENABLE(MEDIA_STREAM)
template<> struct Converter<MediaDeviceInfo::Kind> : DefaultConverter<MediaDeviceInfo::Kind> {
    static MediaDeviceInfo::Kind convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<MediaStreamTrackState> : DefaultConverter<MediaStreamTrackState> {
    static MediaStreamTrackState convert(JSC::ExecState& state, JSC::JSValue value);
};
#endif // ENABLE(MEDIA_STREAM)

#if ENABLE(WEB_RTC)
template<> struct Converter<RTCSignalingState> : DefaultConverter<RTCSignalingState> {
    static RTCSignalingState convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCRtpTransceiverDirection> : DefaultConverter<RTCRtpTransceiverDirection> {
    static RTCRtpTransceiverDirection convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCStatsType> : DefaultConverter<RTCStatsType> {
    static RTCStatsType convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCDegradationPreference> : DefaultConverter<RTCDegradationPreference> {
    static RTCDegradationPreference convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCDtxStatus> : DefaultConverter<RTCDtxStatus> {
    static RTCDtxStatus convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCPriorityType> : DefaultConverter<RTCPriorityType> {
    static RTCPriorityType convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCSdpType> : DefaultConverter<RTCSdpType> {
    static RTCSdpType convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCIceConnectionState> : DefaultConverter<RTCIceConnectionState> {
    static RTCIceConnectionState convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCIceGatheringState> : DefaultConverter<RTCIceGatheringState> {
    static RTCIceGatheringState convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCIceTransportPolicy> : DefaultConverter<RTCIceTransportPolicy> {
    static RTCIceTransportPolicy convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCBundlePolicy> : DefaultConverter<RTCBundlePolicy> {
    static RTCBundlePolicy convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCPeerConnectionState> : DefaultConverter<RTCPeerConnectionState> {
    static RTCPeerConnectionState convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<RTCDataChannelState> : DefaultConverter<RTCDataChannelState> {
    static RTCDataChannelState convert(JSC::ExecState& state, JSC::JSValue value);
};

#endif // ENABLE(WEB_RTC)

template<> struct Converter<FetchOptions::Cache> : DefaultConverter<FetchOptions::Cache> {
    static FetchOptions::Cache convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<FetchOptions::Credentials> : DefaultConverter<FetchOptions::Credentials> {
    static FetchOptions::Credentials convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<FetchOptions::Mode> : DefaultConverter<FetchOptions::Mode> {
    static FetchOptions::Mode convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<FetchOptions::Redirect> : DefaultConverter<FetchOptions::Redirect> {
    static FetchOptions::Redirect convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<FetchReferrerPolicy> : DefaultConverter<FetchReferrerPolicy> {
    static FetchReferrerPolicy convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<FetchOptions::Type> : DefaultConverter<FetchOptions::Type> {
    static FetchOptions::Type convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<FetchOptions::Destination> : DefaultConverter<FetchOptions::Destination> {
    static FetchOptions::Destination convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<ResourceResponseBase::Type> : DefaultConverter<ResourceResponseBase::Type> {
    static ResourceResponseBase::Type convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<FontFaceLoadStatus> : DefaultConverter<FontFaceLoadStatus> {
    static FontFaceLoadStatus convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<FontFaceSetLoadStatus> : DefaultConverter<FontFaceSetLoadStatus> {
    static FontFaceSetLoadStatus convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<CanvasWindingRule> : DefaultConverter<CanvasWindingRule> {
    static CanvasWindingRule convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<AnimationPlayState> : DefaultConverter<AnimationPlayState> {
    static AnimationPlayState convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<AnimationReplaceState> : DefaultConverter<AnimationReplaceState> {
    static AnimationReplaceState convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<ImageBitmapOptions::Orientation> : DefaultConverter<ImageBitmapOptions::Orientation> {
    static ImageBitmapOptions::Orientation convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<ImageBitmapOptions::PremultiplyAlpha> : DefaultConverter<ImageBitmapOptions::PremultiplyAlpha> {
    static ImageBitmapOptions::PremultiplyAlpha convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<ImageBitmapOptions::ColorSpaceConversion> : DefaultConverter<ImageBitmapOptions::ColorSpaceConversion> {
    static ImageBitmapOptions::ColorSpaceConversion convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<ImageBitmapOptions::ResizeQuality> : DefaultConverter<ImageBitmapOptions::ResizeQuality> {
    static ImageBitmapOptions::ResizeQuality convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<PredefinedColorSpace> : DefaultConverter<PredefinedColorSpace> {
    static PredefinedColorSpace convert(JSC::ExecState& state, JSC::JSValue value);
};

#if ENABLE(MEDIA_SOURCE)
template<> struct Converter<SourceBufferAppendMode> : DefaultConverter<SourceBufferAppendMode> {
    static SourceBufferAppendMode convert(JSC::ExecState& state, JSC::JSValue value);
};
#endif // ENABLE(MEDIA_SOURCE)

#if ENABLE(ENCRYPTED_MEDIA)
template<> struct Converter<MediaKeyMessageType> : DefaultConverter<MediaKeyMessageType> {
    static MediaKeyMessageType convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<MediaKeySessionType> : DefaultConverter<MediaKeySessionType> {
    static MediaKeySessionType convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<MediaKeysRequirement> : DefaultConverter<MediaKeysRequirement> {
    static MediaKeysRequirement convert(JSC::ExecState& state, JSC::JSValue value);
};

template<> struct Converter<MediaKeyStatus> : DefaultConverter<MediaKeyStatus> {
    static MediaKeyStatus convert(JSC::ExecState& state, JSC::JSValue value);
};

template<>
struct NativeValueTraits<MediaKeySessionType> {
    static inline void nativeValue(JSC::VM&, JSC::ExecState* exec, JSC::JSValue jsValue, MediaKeySessionType& indexedValue)
    {
    	indexedValue = Converter<MediaKeySessionType>::convert(*exec, jsValue);
    }
};

#endif // ENABLE(ENCRYPTED_MEDIA)

template<typename T> struct Converter<Vector<T> > : DefaultConverter<Vector<T> > {
    static Vector<T> convert(JSC::ExecState& state, JSC::JSValue value)
    {
        return toNativeArray<T>(state, value);
    }
};

template<>
struct NativeValueTraits<Optional<double>> {
	static ALWAYS_INLINE void nativeValue(JSC::VM&, JSC::ExecState* exec, JSC::JSValue jsValue, Optional<double>& indexedValue)
	{
		indexedValue = convert<double>(*exec, jsValue, ShouldAllowNonFiniteNo);
	}
};

template<>
struct NativeValueTraits<CompositeOperation> {
	static ALWAYS_INLINE void nativeValue(JSC::VM&, JSC::ExecState* exec, JSC::JSValue jsValue, CompositeOperation& indexedValue)
	{
		indexedValue = Converter<CompositeOperation>::convert(*exec, jsValue);
	}
};

template<>
struct NativeValueTraits<CompositeOperationOrAuto> {
	static ALWAYS_INLINE void nativeValue(JSC::VM&, JSC::ExecState* exec, JSC::JSValue jsValue, CompositeOperationOrAuto& indexedValue)
	{
		indexedValue = Converter<CompositeOperationOrAuto>::convert(*exec, jsValue);
	}
};

template<> struct Converter<int8_t> : DefaultConverter<int8_t> {
    static int8_t convert(JSC::ExecState& state, JSC::JSValue value, IntegerConversionConfiguration configuration)
    {
		switch (configuration) {
		case NormalConversion:
			break;
		case EnforceRange:
			return toInt8EnforceRange(state, value);
		case Clamp:
			return toInt8Clamp(state, value);
		}
		return toInt8(state, value);
    }
};

template<> struct Converter<uint8_t> : DefaultConverter<uint8_t> {
    static uint8_t convert(JSC::ExecState& state, JSC::JSValue value, IntegerConversionConfiguration configuration)
    {
		switch (configuration) {
		case NormalConversion:
			break;
		case EnforceRange:
			return toUInt8EnforceRange(state, value);
		case Clamp:
			return toUInt8Clamp(state, value);
		}
		return toUInt8(state, value);
	}
};


template<> struct Converter<int16_t> : DefaultConverter<int16_t> {
    static int16_t convert(JSC::ExecState& state, JSC::JSValue value, IntegerConversionConfiguration configuration)
    {
		switch (configuration) {
		case NormalConversion:
			break;
		case EnforceRange:
			return toInt16EnforceRange(state, value);
		case Clamp:
			return toInt16Clamp(state, value);
		}
		return toInt16(state, value);
	}
};

template<> struct Converter<uint16_t> : DefaultConverter<uint16_t> {
    static uint16_t convert(JSC::ExecState& state, JSC::JSValue value, IntegerConversionConfiguration configuration)
    {
		switch (configuration) {
		case NormalConversion:
			break;
		case EnforceRange:
			return toUInt16EnforceRange(state, value);
		case Clamp:
			return toUInt16Clamp(state, value);
		}
		return toUInt16(state, value);
	}
};


template<> struct Converter<int32_t> : DefaultConverter<int32_t> {
    static int32_t convert(JSC::ExecState& state, JSC::JSValue value, IntegerConversionConfiguration configuration)
    {
		switch (configuration) {
		case NormalConversion:
			break;
		case EnforceRange:
			return toInt32EnforceRange(state, value);
		case Clamp:
			return toInt32Clamp(state, value);
		}
		return value.toInt32(&state);
	}
};

template<> struct Converter<uint32_t> : DefaultConverter<uint32_t> {
    static uint32_t convert(JSC::ExecState& state, JSC::JSValue value, IntegerConversionConfiguration configuration)
    {
		switch (configuration) {
		case NormalConversion:
			break;
		case EnforceRange:
			return toUInt32EnforceRange(state, value);
		case Clamp:
			return toUInt32Clamp(state, value);
		}
		return value.toUInt32(&state);
	}
};

template<> struct Converter<int64_t> : DefaultConverter<int64_t> {
    static int64_t convert(JSC::ExecState& state, JSC::JSValue value, IntegerConversionConfiguration configuration)
    {
		if (value.isInt32())
			return value.asInt32();

		switch (configuration) {
		case NormalConversion:
			break;
		case EnforceRange:
			return toInt64EnforceRange(state, value);
		case Clamp:
			return toInt64Clamp(state, value);
		}
		return toInt64(state, value);
	}
};

template<> struct Converter<uint64_t> : DefaultConverter<uint64_t> {
    static uint64_t convert(JSC::ExecState& state, JSC::JSValue value, IntegerConversionConfiguration configuration)
    {
		if (value.isUInt32())
			return value.asUInt32();

		switch (configuration) {
		case NormalConversion:
			break;
		case EnforceRange:
			return toUInt64EnforceRange(state, value);
		case Clamp:
			return toUInt64Clamp(state, value);
		}
		return toUInt64(state, value);
	}
};

template<> struct Converter<ArrayBuffer*> : DefaultConverter<ArrayBuffer> {
	static ArrayBuffer* convert(JSC::ExecState& state, JSC::JSValue value)
	{
		return toArrayBuffer(value);
	}
};

namespace IDLType
{
	template<typename T> inline T nullValue() { return 0; }
	template<typename T> inline bool isNullValue(const T& value) { return false; }
	template<typename T> inline T extractValueFromNullable(const T& value) { return value; }

	template<> inline double nullValue() { return std::numeric_limits<double>::quiet_NaN(); }
	template<> inline bool isNullValue(const double& value) { return std::isnan(value); }

	template<> inline String nullValue() { return String(); }
	template<> inline bool isNullValue(const String& value) { return value.isNull(); }
}

namespace IDLSequence
{
	template<typename T> inline Vector<T> nullValue() { return Vector<T>(); }
	template<typename T> inline bool isNullValue(const Vector<T>& value) { return value.isEmpty(); }
	template<typename T> inline Vector<T> extractValueFromNullable(const Vector<T>& value) { return value; };
}

// Used for IDL enumerations.
template<typename T> Optional<T> parse(JSC::ExecState&, JSC::JSValue);
template<typename T> const char* expectedEnumerationValues();

} // namespace WebCore
