package dk.itu.mario.level;

import java.io.File;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;

import dk.itu.mario.level.PlayerProfile;
import dk.itu.mario.level.grammar.LevelGrammar;

public class GrammarTuner {
	/**
	 * @param args
	 */
	public static void tune(LevelGrammar levelGrammar, PlayerProfile playerProfile, LevelArchetype archetype) {
		KnowledgeBase knowledgeBase = createKnowledgeBase();

		try {
			StatefulKnowledgeSession session = knowledgeBase
					.newStatefulKnowledgeSession();
			session.insert(playerProfile);
			session.fireAllRules();
		} catch (RuntimeException rte) {
			System.out
					.println("Unable to initialize StatefulKnowledgeSession for Rete grammar tuning - all challenges will be enabled!  Exception: ");
			rte.printStackTrace(System.out);
		}
	}

	private static KnowledgeBase createKnowledgeBase() {
		KnowledgeBuilder builder = KnowledgeBuilderFactory
				.newKnowledgeBuilder();

		File accountRules = new File("rules/LevelTunerRules.drl");
		builder.add(ResourceFactory.newFileResource(accountRules),
				ResourceType.DRL);

		if (builder.hasErrors()) {
			throw new RuntimeException(builder.getErrors().toString());
		}

		KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();

		// Add to Knowledge Base packages (rules from the drl file).
		knowledgeBase.addKnowledgePackages(builder.getKnowledgePackages());

		return knowledgeBase;
	}

}