<%--
/**
 * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * Subscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */
--%>

<%@ include file="/html/taglib/ui/asset_categories_selector/init.jsp" %>

<%
String randomNamespace = PortalUtil.generateRandomKey(request, "taglib_ui_asset_categories_selector_page") + StringPool.UNDERLINE;

String className = (String)request.getAttribute("liferay-ui:asset-categories-selector:className");
long classPK = GetterUtil.getLong((String)request.getAttribute("liferay-ui:asset-categories-selector:classPK"));
String curCategoryIds = GetterUtil.getString((String)request.getAttribute("liferay-ui:asset-categories-selector:curCategoryIds"), "");
String curCategoryNames = StringPool.BLANK;
long[] groupIds = (long[])request.getAttribute("liferay-ui:asset-categories-selector:groupIds");
String hiddenInput = (String)request.getAttribute("liferay-ui:asset-categories-selector:hiddenInput");
boolean ignoreRequestValue = GetterUtil.getBoolean(request.getAttribute("liferay-ui:asset-categories-selector:ignoreRequestValue"));
int maxEntries = GetterUtil.getInteger(PropsUtil.get(PropsKeys.ASSET_CATEGORIES_SELECTOR_MAX_ENTRIES));

Group siteGroup = themeDisplay.getSiteGroup();

if (ArrayUtil.isEmpty(groupIds)) {
	groupIds = new long[] {siteGroup.getGroupId()};
}

if (!ArrayUtil.contains(groupIds, themeDisplay.getCompanyGroupId())) {
	groupIds = ArrayUtil.append(groupIds, themeDisplay.getCompanyGroupId());
}

groupIds = ArrayUtil.unique(groupIds);

List<AssetVocabulary> vocabularies = new ArrayList<AssetVocabulary>();

for (int i = 0; i < groupIds.length; i++) {
	vocabularies.addAll(AssetVocabularyServiceUtil.getGroupVocabularies(groupIds[i], false));
}

if (Validator.isNotNull(className)) {
	long classNameId = PortalUtil.getClassNameId(className);

	for (AssetVocabulary vocabulary : vocabularies) {
		vocabulary = vocabulary.toEscapedModel();

		int vocabularyCategoriesCount = AssetCategoryServiceUtil.getVocabularyCategoriesCount(vocabulary.getGroupId(), vocabulary.getVocabularyId());

		if (vocabularyCategoriesCount == 0) {
			continue;
		}

		UnicodeProperties settingsProperties = vocabulary.getSettingsProperties();

		long[] selectedClassNameIds = StringUtil.split(settingsProperties.getProperty("selectedClassNameIds"), 0L);

		if ((selectedClassNameIds.length > 0) && (selectedClassNameIds[0] != AssetCategoryConstants.ALL_CLASS_NAME_IDS) && !ArrayUtil.contains(selectedClassNameIds, classNameId)) {
			continue;
		}

		if (Validator.isNotNull(className) && (classPK > 0)) {
			List<AssetCategory> categories = AssetCategoryServiceUtil.getCategories(className, classPK);

			curCategoryIds = ListUtil.toString(categories, AssetCategory.CATEGORY_ID_ACCESSOR);
			curCategoryNames = ListUtil.toString(categories, AssetCategory.NAME_ACCESSOR);
		}

		if (!ignoreRequestValue) {
			String curCategoryIdsParam = request.getParameter(hiddenInput + StringPool.UNDERLINE + vocabulary.getVocabularyId());

			if (Validator.isNotNull(curCategoryIdsParam)) {
				curCategoryIds = curCategoryIdsParam;
				curCategoryNames = StringPool.BLANK;
			}
		}

		String[] categoryIdsTitles = _getCategoryIdsTitles(curCategoryIds, curCategoryNames, vocabulary.getVocabularyId(), themeDisplay);
	%>

		<span class="field-content">
			<label id="<%= namespace %>assetCategoriesLabel_<%= vocabulary.getVocabularyId() %>">
				<%= vocabulary.getTitle(locale) %>

				<c:if test="<%= vocabulary.getGroupId() == themeDisplay.getCompanyGroupId() %>">
					(<liferay-ui:message key="global" />)
				</c:if>

				<c:if test="<%= vocabulary.isRequired(classNameId) %>">
					<span class="label-required">(<liferay-ui:message key="required" />)</span>
				</c:if>
			</label>

			<div class="lfr-tags-selector-content" id="<%= namespace + randomNamespace %>assetCategoriesSelector_<%= vocabulary.getVocabularyId() %>">
				<aui:input name="<%= hiddenInput + StringPool.UNDERLINE + vocabulary.getVocabularyId() %>" type="hidden" />
			</div>
		</span>

		<aui:script use="liferay-asset-categories-selector">
			new Liferay.AssetCategoriesSelector(
				{
					className: '<%= className %>',
					contentBox: '#<%= namespace + randomNamespace %>assetCategoriesSelector_<%= vocabulary.getVocabularyId() %>',
					curEntries: '<%= HtmlUtil.escapeJS(categoryIdsTitles[1]) %>',
					curEntryIds: '<%= categoryIdsTitles[0] %>',
					hiddenInput: '#<%= namespace + hiddenInput + StringPool.UNDERLINE + vocabulary.getVocabularyId() %>',
					instanceVar: '<%= namespace + randomNamespace %>',
					labelNode: '#<%= namespace %>assetCategoriesLabel_<%= vocabulary.getVocabularyId() %>',
					maxEntries: <%= maxEntries %>,
					moreResultsLabel: '<%= UnicodeLanguageUtil.get(pageContext, "load-more-results") %>',
					portalModelResource: <%= Validator.isNotNull(className) && (ResourceActionsUtil.isPortalModelResource(className) || className.equals(Group.class.getName())) %>,
					singleSelect: <%= !vocabulary.isMultiValued() %>,
					title: '<%= UnicodeLanguageUtil.format(pageContext, "select-x", vocabulary.getTitle(locale), false) %>',
					vocabularyGroupIds: '<%= vocabulary.getGroupId() %>',
					vocabularyIds: '<%= String.valueOf(vocabulary.getVocabularyId()) %>'
				}
			).render();
		</aui:script>

	<%
	}
}
else {
	if (!ignoreRequestValue) {
		String curCategoryIdsParam = request.getParameter(hiddenInput);

		if (curCategoryIdsParam != null) {
			curCategoryIds = curCategoryIdsParam;
		}
	}

	String[] categoryIdsTitles = _getCategoryIdsTitles(curCategoryIds, curCategoryNames, 0, themeDisplay);
%>

	<div class="lfr-tags-selector-content" id="<%= namespace + randomNamespace %>assetCategoriesSelector">
		<aui:input name="<%= hiddenInput %>" type="hidden" />
	</div>

	<aui:script use="liferay-asset-categories-selector">
		new Liferay.AssetCategoriesSelector(
			{
				className: '<%= className %>',
				contentBox: '#<%= namespace + randomNamespace %>assetCategoriesSelector',
				curEntries: '<%= HtmlUtil.escapeJS(categoryIdsTitles[1]) %>',
				curEntryIds: '<%= categoryIdsTitles[0] %>',
				hiddenInput: '#<%= namespace + hiddenInput %>',
				instanceVar: '<%= namespace + randomNamespace %>',
				maxEntries: <%= maxEntries %>,
				moreResultsLabel: '<%= UnicodeLanguageUtil.get(pageContext, "load-more-results") %>',
				portalModelResource: <%= Validator.isNotNull(className) && (ResourceActionsUtil.isPortalModelResource(className) || className.equals(Group.class.getName())) %>,
				vocabularyGroupIds: '<%= StringUtil.merge(groupIds) %>',
				vocabularyIds: '<%= ListUtil.toString(vocabularies, "vocabularyId") %>'
			}
		).render();
	</aui:script>

<%
}
%>

<%!
private long[] _filterCategoryIds(long vocabularyId, long[] categoryIds) throws PortalException, SystemException {
	List<Long> filteredCategoryIds = new ArrayList<Long>();

	for (long categoryId : categoryIds) {
		AssetCategory category = AssetCategoryLocalServiceUtil.fetchCategory(categoryId);

		if (category == null) {
			continue;
		}

		if (category.getVocabularyId() == vocabularyId) {
			filteredCategoryIds.add(category.getCategoryId());
		}
	}

	return ArrayUtil.toArray(filteredCategoryIds.toArray(new Long[filteredCategoryIds.size()]));
}

private String[] _getCategoryIdsTitles(String categoryIds, String categoryNames, long vocabularyId, ThemeDisplay themeDisplay) throws PortalException, SystemException {
	if (Validator.isNotNull(categoryIds)) {
		long[] categoryIdsArray = GetterUtil.getLongValues(StringUtil.split(categoryIds));

		if (vocabularyId > 0) {
			categoryIdsArray = _filterCategoryIds(vocabularyId, categoryIdsArray);
		}

		categoryIds = StringPool.BLANK;
		categoryNames = StringPool.BLANK;

		if (categoryIdsArray.length > 0) {
			StringBundler categoryIdsSb = new StringBundler(categoryIdsArray.length * 2);
			StringBundler categoryNamesSb = new StringBundler(categoryIdsArray.length * 2);

			for (long categoryId : categoryIdsArray) {
				AssetCategory category = AssetCategoryLocalServiceUtil.fetchCategory(categoryId);

				if (category == null) {
					continue;
				}

				categoryIdsSb.append(categoryId);
				categoryIdsSb.append(StringPool.COMMA);

				categoryNamesSb.append(category.getTitle(themeDisplay.getLocale()));
				categoryNamesSb.append(_CATEGORY_SEPARATOR);
			}

			if (categoryIdsSb.index() > 0) {
				categoryIdsSb.setIndex(categoryIdsSb.index() - 1);
				categoryNamesSb.setIndex(categoryNamesSb.index() - 1);

				categoryIds = categoryIdsSb.toString();
				categoryNames = categoryNamesSb.toString();
			}
		}
	}

	return new String[] {categoryIds, categoryNames};
}

private static final String _CATEGORY_SEPARATOR = "_CATEGORY_";
%>