/*
 * Copyright (C) 2013 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.
 */

#ifndef JSDOMPromise_h
#define JSDOMPromise_h

#include "ActiveDOMCallback.h"
#include "JSDOMBinding.h"
#include <heap/StrongInlines.h>
#include <runtime/JSPromiseDeferred.h>

namespace WebCore {

class JSDOMWindow;

class DeferredPromise : public RefCounted<DeferredPromise>, public ActiveDOMCallback {
public:
    static PassRefPtr<DeferredPromise> create(JSC::ExecState* state, JSDOMGlobalObject* globalObject, JSC::JSPromiseDeferred* deferred)
    {
        return adoptRef(new DeferredPromise(state, globalObject, deferred));
    }

    ~DeferredPromise();

    template<class ResolveResultType>
    void resolve(ResolveResultType*);

    template<class ResolveResultType>
    void resolve(const ResolveResultType&);

    template<class RejectResultType>
    void reject(const RejectResultType&);

    void reject(ExceptionCode, const String& message = String());

    JSC::JSValue promise() const;

    bool isSuspended() { return !m_deferred || !canInvokeCallback(); } // The wrapper world has gone away or active DOM objects have been suspended.
    JSDOMGlobalObject* globalObject() { return m_globalObject.get(); }

    void visitAggregate(JSC::SlotVisitor& visitor) { visitor.appendUnbarrieredWeak(&m_deferred); }

private:
    DeferredPromise(JSC::ExecState*, JSDOMGlobalObject*, JSC::JSPromiseDeferred*);

    void clear();
    void contextDestroyed() OVERRIDE;

    void callFunction(JSC::ExecState&, JSC::JSValue function, JSC::JSValue resolution);
    void resolve(JSC::ExecState& state, JSC::JSValue resolution) { callFunction(state, m_deferred->resolve(), resolution); }
    void reject(JSC::ExecState& state, JSC::JSValue resolution) { callFunction(state, m_deferred->reject(), resolution); }

    JSC::Weak<JSC::JSPromiseDeferred> m_deferred;
    JSC::Weak<JSDOMGlobalObject> m_globalObject;
};

RefPtr<DeferredPromise> createDeferredPromise(JSC::ExecState&, JSDOMGlobalObject*);

void fulfillPromiseWithJSON(RefPtr<DeferredPromise>, const String&);
void fulfillPromiseWithArrayBuffer(RefPtr<DeferredPromise>, JSC::ArrayBuffer*);
void fulfillPromiseWithArrayBuffer(RefPtr<DeferredPromise>, const void*, size_t);
void rejectPromiseWithExceptionIfAny(JSC::ExecState&, JSDOMGlobalObject&, JSC::JSPromiseDeferred&);
JSC::EncodedJSValue createRejectedPromiseWithTypeError(JSC::ExecState&, const String&);

inline JSC::JSValue callPromiseFunction(JSC::ExecState& state, JSC::EncodedJSValue promiseFunction(JSC::ExecState*, RefPtr<DeferredPromise>))
{
    JSDOMGlobalObject& globalObject = *JSC::jsCast<JSDOMGlobalObject*>(state.lexicalGlobalObject());
    JSC::JSPromiseDeferred* promiseDeferred = JSC::JSPromiseDeferred::tryCreate(&state, &globalObject);

    // promiseDeferred can be null when terminating a Worker abruptly.
    if (!promiseDeferred)
        return JSC::jsUndefined();

    promiseFunction(&state, DeferredPromise::create(&state, &globalObject, promiseDeferred));

    rejectPromiseWithExceptionIfAny(state, globalObject, *promiseDeferred);
    ASSERT(!state.hadException());
    return promiseDeferred->promise();
}

template <typename Value, typename Error>
class DOMPromise {
public:
	DOMPromise()
	{
	}
    DOMPromise(RefPtr<DeferredPromise> wrapper)
        : m_promiseDeferred(wrapper)
    {
    }
    DOMPromise(const DOMPromise& promise) : m_promiseDeferred(promise.m_promiseDeferred) { }

    void resolve(Value* value) { m_promiseDeferred->resolve<Value>(value); }
    void resolve(const Value& value) { m_promiseDeferred->resolve<Value>(value); }
    void reject(const Error& error) { m_promiseDeferred->reject<Error>(error); }

    JSC::JSValue promise() const { return m_promiseDeferred->promise(); };

private:
    RefPtr<DeferredPromise> m_promiseDeferred;
};

#if 0
template<class ResolveResultType>
inline void DeferredPromise::resolveWithValue(ResolveResultType&& result)
{
    if (isSuspended())
        return;
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    resolve(*exec, toJS(exec, m_globalObject.get(), std::forward<ResolveResultType>(result)));
}

template<class ResolveResultType>
inline void DeferredPromise::resolveWithNewlyCreated(Ref<ResolveResultType>&& result)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    resolve(*exec, toJSNewlyCreated(exec, m_globalObject.get(), WTFMove(result)));
}

template<class RejectResultType>
inline void DeferredPromise::rejectWithValue(RejectResultType&& result)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    reject(*exec, toJS(exec, m_globalObject.get(), std::forward<RejectResultType>(result)));
}
#endif

template<class ResolveResultType>
inline void DeferredPromise::resolve(ResolveResultType* result)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    resolve(*exec, toJS(exec, m_globalObject.get(), result));
}

template<class ResolveResultType>
inline void DeferredPromise::resolve(const ResolveResultType& result)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    resolve(*exec, toJS(exec, m_globalObject.get(), &result));
}

template<class RejectResultType>
inline void DeferredPromise::reject(const RejectResultType& result)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    reject(*exec, toJS(exec, m_globalObject.get(), result));
}

template<>
inline void DeferredPromise::reject(const std::nullptr_t&)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    reject(*exec, JSC::jsNull());
}

template<>
inline void DeferredPromise::reject(const JSC::JSValue& value)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    reject(*exec, value);
}

template<>
inline void DeferredPromise::reject<ExceptionCode>(const ExceptionCode& ec)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    reject(*exec, createDOMException(exec, ec));
}

template<>
inline void DeferredPromise::resolve<String>(const String& result)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    resolve(*exec, jsString(m_globalObject->vm(), result));
}

template<>
inline void DeferredPromise::resolve<bool>(const bool& result)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    resolve(*exec, JSC::jsBoolean(result));
}

template<>
inline void DeferredPromise::resolve<JSC::JSValue>(const JSC::JSValue& value)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    resolve(*exec, value);
}

template<>
inline void DeferredPromise::resolve<Vector<unsigned char> >(const Vector<unsigned char>& result)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    RefPtr<ArrayBuffer> buffer = ArrayBuffer::create(result.data(), result.size());
    resolve(*exec, toJS(exec, m_globalObject.get(), buffer.get()));
}

template<>
inline void DeferredPromise::resolve(const std::nullptr_t&)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    resolve(*exec, JSC::jsUndefined());
}

template<>
inline void DeferredPromise::reject<String>(const String& result)
{
    if (isSuspended())
        return;
    ASSERT(m_deferred);
    ASSERT(m_globalObject);
    JSC::ExecState* exec = m_globalObject->globalExec();
    JSC::JSLockHolder locker(exec);
    reject(*exec, jsString(m_globalObject->vm(), result));
}

}

#endif // JSDOMPromise_h
