/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */

package org.grails.events.rxjava3

import java.util.concurrent.Callable
import java.util.concurrent.ConcurrentHashMap

import groovy.transform.AutoFinal
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j

import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subjects.PublishSubject
import io.reactivex.rxjava3.subjects.Subject

import grails.events.Event
import grails.events.subscriber.Subscriber
import grails.events.subscriber.Subscription
import grails.events.trigger.EventTrigger
import org.grails.events.bus.AbstractEventBus
import org.grails.events.registry.ClosureSubscription
import org.grails.events.registry.EventSubscriberSubscription

/**
 * An EventBus implementation that uses RxJava
 */
@Slf4j
@AutoFinal
@CompileStatic
class RxEventBus extends AbstractEventBus {

    protected final Map<CharSequence, PublishSubject> subjects = new ConcurrentHashMap<CharSequence, PublishSubject>().withDefault {
        PublishSubject.create()
    }

    final Scheduler scheduler

    RxEventBus(Scheduler scheduler = Schedulers.io()) {
        this.scheduler = scheduler
    }

    @Override
    protected Callable buildNotificationCallable(Event event, Collection<Subscription> eventSubscriptions, Closure reply) {
        return {
            PublishSubject sub = subjects.get(event.id)
            if (sub.hasObservers() && !sub.hasComplete()) {
                if (reply != null) {
                    sub.onNext(new EventWithReply(event, reply))
                }
                else {
                    sub.onNext(event)
                }
            }
        }
    }

    @Override
    protected EventSubscriberSubscription buildSubscriberSubscription(CharSequence eventId, Subscriber subscriber) {

        String eventKey = eventId.toString()
        Subject subject = subjects.get(eventKey)

        return new RxEventSubscriberSubscription(eventId, subscriptions, subscriber, subject, scheduler)
    }

    @Override
    protected ClosureSubscription buildClosureSubscription(CharSequence eventId, Closure subscriber) {

        String eventKey = eventId.toString()
        Subject subject = subjects.get(eventKey)

        return new RxClosureSubscription(eventId, subscriptions, subscriber, subject, scheduler)
    }

    private static class RxClosureSubscription extends ClosureSubscription {

        final Disposable subscription

        RxClosureSubscription(CharSequence eventId, Map<CharSequence, Collection<Subscription>> subscriptions, Closure subscriber, Subject subject, Scheduler scheduler) {
            super(eventId, subscriptions, subscriber)
            this.subscription = subject.observeOn(scheduler).subscribe({ eventObject ->
                Event event
                Closure reply = null
                if (eventObject instanceof EventWithReply) {
                    def eventWithReply = (EventWithReply) eventObject
                    event = eventWithReply.event
                    reply = eventWithReply.reply
                }
                else {
                    event = (Event) eventObject
                }

                EventTrigger trigger = buildTrigger(event as Event, reply)
                trigger.proceed()
            } as Consumer, { Throwable t ->
                log.error("Error occurred triggering event listener for event [$eventId]: ${t.message}", t)
            } as Consumer<Throwable>)
        }

        @Override
        Subscription cancel() {
            if (!subscription.disposed) {
                subscription.dispose()
            }
            return super.cancel()
        }

        @Override
        boolean isCancelled() {
            return subscription.disposed
        }
    }

    private static class RxEventSubscriberSubscription extends EventSubscriberSubscription {

        final Disposable subscription

        RxEventSubscriberSubscription(CharSequence eventId, Map<CharSequence, Collection<Subscription>> subscriptions, Subscriber subscriber, Subject subject, Scheduler scheduler) {
            super(eventId, subscriptions, subscriber)
            this.subscription = subject.observeOn(scheduler).subscribe({ event ->
                EventTrigger trigger = buildTrigger(event as Event)
                trigger.proceed()
            } as Consumer, { Throwable t ->
                log.error("Error occurred triggering event listener for event [$eventId]: ${t.message}", t)
            } as Consumer<Throwable>)
        }

        @Override
        Subscription cancel() {
            if (!subscription.disposed) {
                subscription.dispose()
            }
            return super.cancel()
        }

        @Override
        boolean isCancelled() {
            return subscription.disposed
        }
    }
}
