package common.village;

import java.util.ArrayList;

import common.collect.Lists;
import common.item.ItemStack;
import common.tags.TagObject;
import java.util.List;

public class MerchantRecipeList extends ArrayList<MerchantRecipe> {
	public MerchantRecipe canUse(ItemStack stack1, ItemStack stack2, int index) {
		if(index > 0 && index < this.size()) {
			MerchantRecipe recipe = this.get(index);
			return !areItemsSimilar(stack1, recipe.first())
					|| (stack2 != null || recipe.both())
							&& (!recipe.both() || !areItemsSimilar(stack2, recipe.second()))
					|| stack1.size < recipe.first().size
					|| recipe.both() && stack2.size < recipe.second().size ? null : recipe;
		}
		else {
			for(int z = 0; z < this.size(); z++) {
				MerchantRecipe recipe = this.get(z);
				if(areItemsSimilar(stack1, recipe.first()) && stack1.size >= recipe.first().size
						&& (!recipe.both() && stack2 == null
								|| recipe.both() && areItemsSimilar(stack2, recipe.second())
										&& stack2.size >= recipe.second().size)) {
					return recipe;
				}
			}
			return null;
		}
	}

	private static boolean areItemsSimilar(ItemStack stack1, ItemStack stack2) {
		return ItemStack.areItemsEqual(stack1, stack2)
				&& (!stack2.hasTagCompound() || stack1.hasTagCompound() && TagObject.compare(stack2.getTagCompound(), stack1.getTagCompound()));
	}

	public void fromTags(List<TagObject> list) {
		this.clear();
		for(int z = 0; z < list.size(); z++) {
			this.add(new MerchantRecipe(list.get(z)));
		}
	}

	public List<TagObject> toTags() {
		List<TagObject> list = Lists.newArrayList();
		for(int z = 0; z < this.size(); z++) {
			list.add(this.get(z).toTags());
		}
		return list;
	}
}
