
package org.apache.asterix.metadata.feeds;

import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.asterix.common.exceptions.AsterixException;
import org.apache.asterix.common.feeds.api.IFeedLifecycleEventSubscriber;

public class FeedLifecycleEventSubscriber implements IFeedLifecycleEventSubscriber {

    private LinkedBlockingQueue<FeedLifecycleEvent> inbox;

    public FeedLifecycleEventSubscriber() {
        this.inbox = new LinkedBlockingQueue<FeedLifecycleEvent>();
    }

    @Override
    public void handleFeedEvent(FeedLifecycleEvent event) {
        inbox.add(event);
    }

    @Override
    public void assertEvent(FeedLifecycleEvent event) throws AsterixException, InterruptedException {
        boolean eventOccurred = false;
        FeedLifecycleEvent e = null;
        Iterator<FeedLifecycleEvent> eventsSoFar = inbox.iterator();
        while (eventsSoFar.hasNext()) {
            e = eventsSoFar.next();
            assertNoFailure(e);
            eventOccurred = e.equals(event);
        }

        while (!eventOccurred) {
            e = inbox.take();
            eventOccurred = e.equals(event);
            if (!eventOccurred) {
                assertNoFailure(e);
            }
        }
    }

    private void assertNoFailure(FeedLifecycleEvent e) throws AsterixException {
        if (e.equals(FeedLifecycleEvent.FEED_INTAKE_FAILURE) || e.equals(FeedLifecycleEvent.FEED_COLLECT_FAILURE)) {
            throw new AsterixException("Failure in feed");
        }
    }

}
