package org.javacodegeeks.examples.v3.bus;

import reactor.core.Disposable;
import reactor.core.scheduler.Schedulers;

import java.time.Duration;
import java.util.stream.IntStream;

public class ReactorEventBusMain {
    public static void main(String[] args) throws InterruptedException {
        ReactorEventBusImpl<Integer> bus = new ReactorEventBusImpl<>();


        final var firstSubscription = subscribeToBus(bus, 0);

        Thread.sleep(Duration.ofSeconds(1));

        System.out.println("Sending 1..10");
        IntStream.range(1, 11)
            .forEach(bus::publish);

        Thread.sleep(Duration.ofSeconds(1));

        final var secondSubscription = subscribeToBus(bus, 1);

        Thread.sleep(Duration.ofSeconds(1));

        System.out.println("Sending 11..20");
        IntStream.range(11, 21)
            .forEach(bus::publish);
        Thread.sleep(Duration.ofMinutes(1));
    }

    private static Disposable subscribeToBus(ReactorEventBusImpl<Integer> bus, Integer subscribtionNumber) {
        return bus.receive()
            .subscribeOn(Schedulers.boundedElastic())
            .doOnNext(i -> System.out.printf("[%s][%s] got %s\n", subscribtionNumber, Thread.currentThread().getName(), i))
            .subscribe();
    }
}
