package de.siphalor.was.content.product;

import de.siphalor.was.content.ContentManager;
import de.siphalor.was.content.product.dynamic.DynamicProductType;
import de.siphalor.was.util.ResourceManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class ProductManager implements ResourceManager<ProductType<?>> {
	private final Map<String, ProductType<?>> productTypes = new HashMap<>();

	@Override
	public void clear() {
		productTypes.clear();
	}

	public void reload(@NotNull ContentManager contentManager) {
		contentManager.getResources("products", "properties").forEach(resource -> {
			InputStream inputStream = resource.getInputStream();
			if (inputStream != null) {
				productTypes.put(resource.getId(), DynamicProductType.from(resource.getId(), inputStream));
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	@Nullable
	public ProductType<?> get(String id) {
		return productTypes.get(id);
	}

	@NotNull
	public Collection<ProductType<?>> getTypes() {
		return productTypes.values();
	}

	@Nullable
	public Product randomProduct(Random random) {
		if (!productTypes.isEmpty()) {
			List<ProductType<?>> typeList = new ArrayList<>(productTypes.values());
			return typeList.get(random.nextInt(typeList.size())).randomProduct(random);
		}
		return null;
	}
}
