package org.broadleafcommerce.core.web.dialect.catalog;

import java.util.List;

import org.broadleafcommerce.core.catalog.domain.Category;
import org.broadleafcommerce.core.catalog.service.CatalogService;
import org.broadleafcommerce.core.web.dialect.AbstractModelVariableModifierProcessor;
import org.broadleafcommerce.core.web.dialect.ProcessorUtils;
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;

/**
 * @author apazzolini
 *
 */
public class CategoriesProcessor extends AbstractModelVariableModifierProcessor {

	/**
	 * Sets the name of this processor to be used in Thymeleaf template
	 */
	public CategoriesProcessor() {
		super("categories");
	}
	
	@Override
	public int getPrecedence() {
		return 10000;
	}

	@Override
	protected void modifyModelAttributes(Arguments arguments, Element element) {
		CatalogService catalogService = ProcessorUtils.getCatalogService(arguments);
		
		String resultVar = element.getAttributeValueFromNormalizedName("resultvar");
		String parentCategory = element.getAttributeValueFromNormalizedName("parentcategory");
		
		// TODO: Potentially write an algorithm that will pick the minimum depth category
		// instead of the first category in the list
		List<Category> categories = catalogService.findCategoriesByName(parentCategory);
		if (categories != null && categories.size() > 0) {
			addToModel(resultVar, catalogService.findAllSubCategories(categories.get(0)));
		}
	}
}

@@ -74,16 +74,60 @@
 .List;%0A%0A
+import org.apache.commons.lang.StringUtils;%0A
 import o
@@ -995,34 +995,16 @@
 alue
-FromNormalizedName
 (%22result
 var%22
@@ -999,17 +999,17 @@
 (%22result
-v
+V
 ar%22);%0A%09%09
@@ -1061,34 +1061,16 @@
 alue
-FromNormalizedName
 (%22parent
 cate
@@ -1065,17 +1065,17 @@
 (%22parent
-c
+C
 ategory%22
@@ -1077,16 +1077,87 @@
 gory%22);%0A
+%09%09String unparsedMaxResults = element.getAttributeValue(%22maxResults%22);%0A
 %09%09%0A%09%09// 
@@ -1425,29 +1425,38 @@
 %0A%09%09%09
-addToModel(resultVar,
+List%3CCategory%3E subcategories =
  cat
@@ -1506,16 +1506,235 @@
 .get(0))
+;%0A%09%09%09if (StringUtils.isNotEmpty(unparsedMaxResults)) %7B%0A%09%09%09%09int maxResults = Integer.parseInt(unparsedMaxResults);%0A%09%09%09%09subcategories = subcategories.subList(0, maxResults);%0A%09%09%09%7D%0A%09%09%09%0A%09%09%09addToModel(resultVar, subcategories
 );%0A%09%09%7D%0A%09

Add "maxResults" to the CategoriesProcessor