package de.siphalor.was.content.quest;

import de.siphalor.was.content.ContentManager;
import de.siphalor.was.content.product.ProductManager;
import de.siphalor.was.util.ResourceManager;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * This class handles the loading and access of quest generators.
 */
public class QuestManager implements ResourceManager<QuestGenerator> {
	/**
	 * All of the quest generators mapped by their ids
	 */
	private final Map<String, QuestGenerator> questGenerators = new HashMap<>();

	/**
	 * Clears all loaded quest generators.
	 */
	@Override
	public void clear() {
		questGenerators.clear();
	}

	/**
	 * Loads all quest generators from the given content manager
	 * @param contentManager The content manager to load from
	 * @param productManager The product manager to check product definitions against
	 */
	public void reload(@NotNull ContentManager contentManager, @NotNull ProductManager productManager) {
		contentManager.getResources("quests", "csv").forEach(resource -> {
			InputStream inputStream = resource.getInputStream();
			if (inputStream != null) {
				questGenerators.put(resource.getId(), StaticQuestGenerator.fromCsv(inputStream, productManager));
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Gets a quest generator by its id.
	 * @param id The id
	 * @return The associated quest generator
	 */
	@Override
	public QuestGenerator get(String id) {
		return questGenerators.get(id);
	}

	@Override
	public void register(String id, QuestGenerator value) {
		questGenerators.put(id, value);
	}

	/**
	 * Gets all of the quest ids.
	 * @return The quest ids
	 */
	public Set<String> ids() {
		return questGenerators.keySet();
	}
}
