package com.hammurapi.reasoning.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import com.hammurapi.convert.ConvertingService;
import com.hammurapi.reasoning.spi.Superseder;

/**
 * Compacts collections of facts by removing facts superseded
 * by other facts in the collection. 
 * @author Pavel Vlasov
 *
 */
public class KnowledgeCompactor {

	@SuppressWarnings("unchecked")
	static <F> Collection<F> compact(Collection<F> input) {
		F[] elements = (F[]) new Object[input.size()];
		Iterator<F> it = input.iterator();
		for (int i=0; it.hasNext(); ++i) {
			elements[i] = it.next();
		}
		
		for (int i=0; i<elements.length; ++i) {
			if (elements[i]!=null) {
				Superseder superseder = ConvertingService.convert(elements[i], Superseder.class);
				if (superseder!=null) {
					for (int j=0; j<elements.length; ++j) {
						if (j!=i && elements[j]!=null && superseder.supersedes(elements[j])) {
							elements[j] = null;
						}
					}
				}
			}
		}
		
		Collection<F> ret = new ArrayList<F>();
		for (F element: elements) {
			if (element!=null) {
				ret.add(element);
			}
		}
		return ret;
	}
}
