package de.ugoe.cs.autoquest.plugin.usability2.rules.operator.transformer;

import java.util.Iterator;

import de.ugoe.cs.autoquest.plugin.usability2.rules.operator.IFilter;
import de.ugoe.cs.autoquest.plugin.usability2.rules.operator.IResultTransformer;
import de.ugoe.cs.autoquest.plugin.usability2.rules.results.IMatch;
import de.ugoe.cs.autoquest.plugin.usability2.rules.results.IResult;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITask;

public class UniqueResultsTransformer implements IResultTransformer {

    public static final IResultTransformer UNIQUE_RESULTS_TRANSFORMER = new UniqueResultsTransformer();
    
    private UniqueResultsTransformer(){
        super();
    }
    
    private static class UniqueResult implements IResult {

        final IResult result;
        
        private UniqueResult(IResult result) {
            this.result = result;
        }
        
        /* (non-Javadoc)
         * @see java.lang.Iterable#iterator()
         */
        @Override
        public Iterator<IMatch> iterator() {
            return new Iterator<IMatch>() {
                IMatch last = null;
                Iterator<IMatch> inner = result.iterator();
                
                @Override
                public boolean hasNext() {
                    boolean result;
                    if (last == null) {
                        result = inner.hasNext();
                        if(result)
                            last = inner.next();
                        return result;
                    }
                    
                    while((result = inner.hasNext())) {
                        IMatch cur = inner.next();
                        if (!cur.getTask().equals(last.getTask())) {
                            last = cur;
                            return true;
                        }
                    }
                    return false;
                }

                @Override
                public IMatch next() {
                    return last;
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }
                
            };
        }

        /* (non-Javadoc)
         * @see de.ugoe.cs.autoquest.usability.rules.patterns.operator.IResult#isPresent()
         */
        @Override
        public boolean isPresent() {
            return result.isPresent();
        }
    }
    
    @Override
    public IResult transform(IResult result, IFilter filter, ITask task) {
        return new UniqueResult(result);
    }

}
