package org.jeeventstore.core.store;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jeeventstore.core.ChangeSet;
import org.jeeventstore.core.ConcurrencyException;
import org.jeeventstore.core.persistence.EventStorePersistence;

/**
 *
 * @author Alexander Langer
 */
public class MockPersistence implements EventStorePersistence {

    private final String bucketId;
    private final String streamId;
    private final List<ChangeSet> changeSets = new ArrayList<>();

    public MockPersistence(String bucketId, String streamId) {
        this.bucketId = bucketId;
        this.streamId = streamId;
    }

    @Override
    public boolean existsStream(String bucketId, String streamId) {
        return true;
    }

    @Override
    public Iterator<ChangeSet> allChanges() {
        return changeSets.iterator();
    }

    @Override
    public Iterator<ChangeSet> getFrom(String bucketId, String streamId, long minVersion, long maxVersion) {
        if (!this.bucketId.equals(bucketId) || !this.streamId.equals(streamId))
            return new ArrayList<ChangeSet>().iterator();
        int max = Math.min(changeSets.size(), (int) maxVersion);
        int min = Math.min(changeSets.size(), (int) minVersion);
        return changeSets.subList(min, max).iterator();
    }

    @Override
    public void persistChanges(ChangeSet changeSet) throws ConcurrencyException {
        // version 0 -> changeset.size() == 0, i.e. wrong if size > 0 
        // version 1 -> size == 1
        // etc

        // we add the changeSet first, such that we can ignore the
        // exception in tests where we actually want to create an invalid stream.
        changeSets.add(changeSet);
        if (changeSets.size() != changeSet.streamVersion())
            throw new ConcurrencyException();
    }
    
}

@@ -385,64 +385,43 @@
 ate 
-final String bucketId;%0A    private final String streamId
+static final String RESET = %22RESET%22
 ;%0A  
@@ -516,115 +516,11 @@
 nce(
-String bucketId, String streamId) %7B%0A        this.bucketId = bucketId;%0A        this.streamId = streamId;%0A   
+) %7B
  %7D%0A%0A
@@ -620,12 +620,29 @@
 urn 
-true
+!changeSets.isEmpty()
 ;%0A  
@@ -890,132 +890,80 @@
 if (
-!this.bucketId.equals(bucketId) %7C%7C !this.streamId.equals(streamId))%0A            return new ArrayList%3CChangeSet%3E().iterator()
+maxVersion == Long.MAX_VALUE)%0A            maxVersion = Integer.MAX_VALUE
 ;%0A  
@@ -1249,16 +1249,123 @@
 ption %7B%0A
+        if (RESET.equals(changeSet.bucketId()) %7B%0A            this.cleanup();%0A            return;%0A        %7D%0A
         
@@ -1721,16 +1721,16 @@
 sion())%0A
-
         
@@ -1768,20 +1768,177 @@
 ion();%0A    %7D
+%0A%0A    private void cleanup() %7B%0A        changeSets.clear();%0A    %7D%0A%0A    public static ChangeSet resetCommand() %7B%0A        return new TestChangeSet(RESET);%0A    %7D
 %0A    %0A%7D%0A

Use a special RESET comment in MockPersistence to clean up.