package com.timgroup.eventsubscription;

import com.timgroup.eventstore.api.EventInStream;
import com.timgroup.eventstore.api.EventReader;
import com.timgroup.eventstore.api.EventStore;
import com.timgroup.eventstore.api.LegacyPositionAdapter;
import com.timgroup.eventstore.api.Position;
import com.timgroup.eventstore.api.ResolvedEvent;

import java.time.Instant;
import java.util.stream.Stream;

import static com.timgroup.eventstore.api.EventRecord.eventRecord;
import static com.timgroup.eventstore.api.StreamId.streamId;

public class LegacyEventStoreEventReaderAdapter implements EventReader {
    private final EventStore eventStore;

    public LegacyEventStoreEventReaderAdapter(EventStore eventStore) {
        this.eventStore = eventStore;
    }

    @Override
    public Stream<ResolvedEvent> readAllForwards() {
        return eventStore.streamingFromAll(0).map(this::toResolvedEvent);
    }

    @Override
    public Stream<ResolvedEvent> readAllForwards(Position positionExclusive) {
        return eventStore.streamingFromAll(((LegacyPositionAdapter) positionExclusive).version()).map(this::toResolvedEvent);
    }

    @Override
    public Position emptyStorePosition() {
        return new LegacyPositionAdapter(0);
    }

    private ResolvedEvent toResolvedEvent(EventInStream eventInStream) {
        return new ResolvedEvent(
                new LegacyPositionAdapter(eventInStream.version()),
                eventRecord(
                        Instant.ofEpochMilli(eventInStream.effectiveTimestamp().getMillis()),
                        streamId("all", "all"),
                        eventInStream.version(),
                        eventInStream.eventData().eventType(),
                        eventInStream.eventData().body().data(),
                        new byte[0]
                )
        );
    }
}

@@ -179,16 +179,70 @@
 tStore;%0A
+import com.timgroup.eventstore.api.EventStreamReader;%0A
 import c
@@ -385,16 +385,61 @@
 edEvent;
+%0Aimport com.timgroup.eventstore.api.StreamId;
 %0A%0Aimport
@@ -690,16 +690,35 @@
 ntReader
+, EventStreamReader
  %7B%0A    p
@@ -1946,11 +1946,374 @@
 );%0A    %7D
+%0A%0A    @Override%0A    public Stream%3CResolvedEvent%3E readStreamForwards(StreamId streamId, long eventNumber) %7B%0A        if (!streamId.equals(streamId(%22all%22, %22all%22))) %7B%0A            throw new IllegalArgumentException(%22Cannot read %22 + streamId + %22 using legacy adapter%22);%0A        %7D%0A        return eventStore.streamingFromAll(eventNumber).map(this::toResolvedEvent);%0A    %7D
 %0A%7D%0A

implement EventStreamReader in legacy adapter