<%--
/**
 * Copyright (c) 2000-present 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.
 *
 *
 *
 */
--%>

<%
UnicodeProperties unicodeProperties = commerceDiscountRule.getSettingsProperties();

String typeSettings = unicodeProperties.getProperty(commerceDiscountRule.getType());
%>

<div class="col-12">
	<div id="item-finder-root"></div>

	<aui:input id="typeSettings" name="typeSettings" type="hidden" value="<%= (typeSettings == null) ? StringPool.BLANK : typeSettings %>" />

	<aui:script require="commerce-frontend-js/components/item_finder/entry as itemFinder, commerce-frontend-js/utilities/slugify as slugify, commerce-frontend-js/utilities/eventsDefinitions as events, commerce-frontend-js/ServiceProvider/index as ServiceProvider">
		var CommerceDiscountRuleResource = ServiceProvider.default.AdminPricingAPI(
			'v2'
		);

		var form = document.getElementById('<portlet:namespace />fm');

		var name = form.querySelector('#<portlet:namespace />name').value;

		var commerceDiscountRuleType = form.querySelector('#<portlet:namespace />type')
			.value;
		var typeSettings = form.querySelector('#<portlet:namespace />typeSettings')
			.value;

		function addProductDefinition(productId) {
			if (typeSettings === '') {
				return typeSettings.concat(productId);
			}
			return typeSettings.concat(',').concat(productId);
		}

		function selectItem(product) {
			var ruleData = {
				name: name,
				type: commerceDiscountRuleType,
				typeSettings: addProductDefinition(product.id),
			};

			return CommerceDiscountRuleResource.updateDiscountRule(
				'<%= commerceDiscountRule.getCommerceDiscountRuleId() %>',
				ruleData
			)
				.then(function (payload) {
					Liferay.fire(events.UPDATE_DATASET_DISPLAY, {
						id:
							'<%= CommercePricingDataSetConstants.COMMERCE_DATA_SET_KEY_DISCOUNT_RULE_PRODUCT_DEFINITIONS %>',
					});

					typeSettings = payload.typeSettings
						.replace(/(\r\n|\n|\r)/gm, '')
						.split('=')[1];

					document.getElementById(
						'<portlet:namespace />typeSettings'
					).value = typeSettings;
				})
				.catch(function (error) {
					return Promise.reject(error);
				});
		}

		function getSelectedItems() {
			return Promise.resolve([]);
		}

		itemFinder.default('itemFinder', 'item-finder-root', {
			apiUrl:
				'/o/headless-commerce-admin-catalog/v1.0/products?nestedFields=catalog',
			getSelectedItems: getSelectedItems,
			inputPlaceholder: '<%= LanguageUtil.get(request, "find-a-product") %>',
			linkedDatasetsId: [
				'<%= CommercePricingDataSetConstants.COMMERCE_DATA_SET_KEY_DISCOUNT_RULE_PRODUCT_DEFINITIONS %>',
			],
			itemCreation: false,
			itemSelectedMessage: '<%= LanguageUtil.get(request, "product-selected") %>',
			itemsKey: 'id',
			onItemSelected: selectItem,
			pageSize: 10,
			panelHeaderLabel: '<%= LanguageUtil.get(request, "add-products") %>',
			portletId: '<%= portletDisplay.getRootPortletId() %>',
			schema: [
				{
					fieldName: ['name', 'LANG'],
				},
				{
					fieldName: 'skuFormatted',
				},
				{
					fieldName: ['catalog', 'name'],
				},
			],
			spritemap: '<%= themeDisplay.getPathThemeImages() %>/lexicon/icons.svg',
			titleLabel: '<%= LanguageUtil.get(request, "add-existing-product") %>',
		});
	</aui:script>
</div>

<div class="col-12">
	<commerce-ui:panel
		bodyClasses="p-0"
		title='<%= LanguageUtil.get(request, "products") %>'
	>
		<clay:data-set-display
			contextParams='<%=
				HashMapBuilder.<String, String>put(
					"commerceDiscountRuleId", String.valueOf(commerceDiscountRule.getCommerceDiscountRuleId())
				).build()
			%>'
			dataProviderKey="<%= CommercePricingDataSetConstants.COMMERCE_DATA_SET_KEY_DISCOUNT_RULE_PRODUCT_DEFINITIONS %>"
			formId="fm"
			id="<%= CommercePricingDataSetConstants.COMMERCE_DATA_SET_KEY_DISCOUNT_RULE_PRODUCT_DEFINITIONS %>"
			itemsPerPage="<%= 10 %>"
			namespace="<%= liferayPortletResponse.getNamespace() %>"
			pageNumber="<%= 1 %>"
			portletURL="<%= currentURLObj %>"
		/>
	</commerce-ui:panel>
</div>