/*
 * Copyright (C) 2024 Marais Rossouw <me@marais.co>. 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.
 */

#include "config.h"
#include "InternalObserverReduce.h"

#include "AbortSignal.h"
#include "ContextDestructionObserverInlines.h"
#include "Exception.h"
#include "ExceptionCode.h"
#include "InternalObserver.h"
#include "JSDOMConvertAny.h"
#include "JSDOMPromiseDeferred.h"
#include "JSValueInWrappedObjectInlines.h"
#include "Observable.h"
#include "ReducerCallback.h"
#include "ScriptExecutionContext.h"
#include "ScriptWrappableInlines.h"
#include "SubscribeOptions.h"
#include "Subscriber.h"
#include "SubscriberCallback.h"
#include <JavaScriptCore/JSCJSValueInlines.h>

namespace WebCore {

class InternalObserverReduce final : public InternalObserver {
public:
    static Ref<InternalObserverReduce> create(ScriptExecutionContext& context, Ref<AbortSignal>&& signal, Ref<ReducerCallback>&& callback, JSC::JSValue initialValue, Ref<DeferredPromise>&& promise)
    {
        Ref internalObserver = adoptRef(*new InternalObserverReduce(context, WTF::move(signal), WTF::move(callback), initialValue, WTF::move(promise)));
        internalObserver->suspendIfNeeded();
        return internalObserver;
    }

private:
    void next(JSC::JSValue value) final
    {
        auto* globalObject = protect(scriptExecutionContext())->globalObject();
        ASSERT(globalObject);

        if (!m_accumulator) {
            m_index++;
            auto* owner = subscriber() ? subscriber()->wrapper() : nullptr;
            m_accumulator.set(*globalObject, owner, value);
            return;
        }

        Ref vm = globalObject->vm();

        JSC::JSLockHolder lock(vm);
        auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm);

        auto result = protect(m_callback)->invokeRethrowingException(m_accumulator.getValue(), value, m_index++);

        JSC::Exception* exception = scope.exception();
        if (exception) [[unlikely]] {
            scope.clearException();
            auto value = exception->value();
            protect(m_promise)->reject<IDLAny>(value);
            Ref { m_signal }->signalAbort(value);
        }

        if (result.type() == CallbackResultType::Success) {
            auto* owner = subscriber() ? subscriber()->wrapper() : nullptr;
            m_accumulator.set(*globalObject, owner, result.releaseReturnValue());
        }
    }

    void error(JSC::JSValue value) final
    {
        protect(m_promise)->reject<IDLAny>(value);
    }

    void complete() final
    {
        InternalObserver::complete();

        if (!m_accumulator) [[unlikely]] {
            protect(m_promise)->reject(Exception { ExceptionCode::TypeError, "No inital value for Observable with no values"_s });
            return;
        }

        protect(m_promise)->resolve<IDLAny>(m_accumulator.getValue());
    }

    void visitAdditionalChildrenInGCThread(JSC::AbstractSlotVisitor& visitor) const final
    {
        m_callback->visitJSFunctionInGCThread(visitor);
        m_accumulator.visitInGCThread(visitor);
    }

    InternalObserverReduce(ScriptExecutionContext& context, Ref<AbortSignal>&& signal, Ref<ReducerCallback>&& callback, JSC::JSValue initialValue, Ref<DeferredPromise>&& promise)
        : InternalObserver(context)
        , m_signal(WTF::move(signal))
        , m_callback(WTF::move(callback))
        , m_promise(WTF::move(promise))
    {
        if (!initialValue.isUndefined()) [[unlikely]] {
            auto* owner = subscriber() ? subscriber()->wrapper() : nullptr;
            if (auto* globalObject = context.globalObject())
                m_accumulator.set(*globalObject, owner, initialValue);
        }
    }

    uint64_t m_index { 0 };
    const Ref<AbortSignal> m_signal;
    const Ref<ReducerCallback> m_callback;
    JSValueInWrappedObject m_accumulator;
    const Ref<DeferredPromise> m_promise;
};

void createInternalObserverOperatorReduce(ScriptExecutionContext& context, Observable& observable, Ref<ReducerCallback>&& callback, JSC::JSValue initialValue, SubscribeOptions&& options, Ref<DeferredPromise>&& promise)
{
    Ref signal = AbortSignal::create(&context);

    Vector<Ref<AbortSignal>> dependentSignals = { signal };
    if (options.signal)
        dependentSignals.append(options.signal.releaseNonNull());
    Ref dependentSignal = AbortSignal::any(context, dependentSignals);

    if (dependentSignal->aborted())
        return promise->reject<IDLAny>(dependentSignal->reason().getValue());

    dependentSignal->addAlgorithm([promise](JSC::JSValue reason) {
        promise->reject<IDLAny>(reason);
    });

    Ref observer = InternalObserverReduce::create(context, WTF::move(signal), WTF::move(callback), initialValue, WTF::move(promise));
    observable.subscribeInternal(context, WTF::move(observer), SubscribeOptions { .signal = WTF::move(dependentSignal) });
}

} // namespace WebCore
