package eu.dnetlib.data.collector.plugins.httpfilename;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Created by miriam on 25/06/2018.
 */
public class HttpWithFileNameCollectorIterator implements Iterator<String> {
    public static final String TERMINATOR = "FINITO";
    private static final Log log = LogFactory.getLog(HttpWithFileNameCollectorIterator.class);

     private final ArrayBlockingQueue<String> queue;

    public static final long waitTime = 60L;

    private String last = "<resource><DOI>JUNK</DOI></resource>";

    public HttpWithFileNameCollectorIterator(ArrayBlockingQueue<String> queue) {
        this.queue = queue;
        extractFromQueue();
    }

    @Override
        public boolean hasNext() {


            //return !(Objects.equals(last, TERMINATOR) || Objects.equals(last,null));
            return !(Objects.equals(last, TERMINATOR));
        }

        @Override
        public String next() {
            try{

                return last;

            }finally{
                extractFromQueue();
            }

        }

    private void extractFromQueue() {


        try {
            last = queue.take();
            //last = queue.poll(waitTime, TimeUnit.SECONDS);
        }catch(InterruptedException e){
            log.warn("Interrupted while waiting for element to consume");
            throw new NoSuchElementException(e.getMessage());
        }
    }


}
