<%--
/**
 * 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.
 *
 *
 *
 */
--%>

<%@ include file="/init.jsp" %>

<%
String className = ParamUtil.getString(request, "className");
long classTypeId = ParamUtil.getLong(request, "classTypeId");
String ddmStructureFieldName = ParamUtil.getString(request, "ddmStructureFieldName");
Serializable ddmStructureFieldValue = ParamUtil.getString(request, "ddmStructureFieldValue");
String eventName = ParamUtil.getString(request, "eventName", liferayPortletResponse.getNamespace() + "selectDDMStructureField");

AssetRendererFactory<?> assetRendererFactory = AssetRendererFactoryRegistryUtil.getAssetRendererFactoryByClassName(className);

ClassTypeReader classTypeReader = assetRendererFactory.getClassTypeReader();

ClassType classType = classTypeReader.getClassType(classTypeId, locale);

PortletURL portletURL = renderResponse.createRenderURL();

portletURL.setParameter("mvcPath", "/asset_list/select_structure_field.jsp");
portletURL.setParameter("className", className);
portletURL.setParameter("classTypeId", String.valueOf(classTypeId));
portletURL.setParameter("eventName", eventName);
%>

<div class="alert alert-danger hide" id="<portlet:namespace />message">
	<span class="error-message"><liferay-ui:message key="the-field-value-is-invalid" /></span>
</div>

<clay:container-fluid
	id='<%= liferayPortletResponse.getNamespace() + "selectDDMStructureFieldForm" %>'
>
	<liferay-ui:search-container
		iteratorURL="<%= portletURL %>"
		total="<%= classType.getClassTypeFieldsCount() %>"
	>
		<liferay-ui:search-container-results
			results="<%= classType.getClassTypeFields(searchContainer.getStart(), searchContainer.getEnd()) %>"
		/>

		<liferay-ui:search-container-row
			className="com.liferay.asset.kernel.model.ClassTypeField"
			modelVar="field"
		>
			<liferay-ui:search-container-column-text>
				<input data-button-id="<%= liferayPortletResponse.getNamespace() %>applyButton<%= field.getName() %>" data-form-id="<%= liferayPortletResponse.getNamespace() + field.getName() %>fieldForm" name="<portlet:namespace />selectStructureFieldSubtype" type="radio" <%= Objects.equals(field.getName(), ddmStructureFieldName) ? "checked" : StringPool.BLANK %> />
			</liferay-ui:search-container-column-text>

			<%
			String fieldsNamespace = StringUtil.randomId();
			%>

			<liferay-ui:search-container-column-text
				name="field"
			>
				<liferay-portlet:resourceURL copyCurrentRenderParameters="<%= false %>" id="/asset_list/get_field_value" var="structureFieldURL">
					<portlet:param name="structureId" value="<%= String.valueOf(field.getClassTypeId()) %>" />
					<portlet:param name="name" value="<%= field.getName() %>" />
					<portlet:param name="fieldsNamespace" value="<%= fieldsNamespace %>" />
				</liferay-portlet:resourceURL>

				<aui:form action="<%= structureFieldURL %>" disabled="<%= !Objects.equals(field.getName(), ddmStructureFieldName) %>" name='<%= field.getName() + "fieldForm" %>' onSubmit="event.preventDefault()">
					<aui:input disabled="<%= true %>" name="buttonId" type="hidden" value='<%= liferayPortletResponse.getNamespace() + "applyButton" + field.getName() %>' />

					<%
					Field ddmField = new com.liferay.dynamic.data.mapping.storage.Field();

					ddmField.setDefaultLocale(themeDisplay.getLocale());
					ddmField.setDDMStructureId(field.getClassTypeId());
					ddmField.setName(field.getName());

					if (Objects.equals(field.getName(), ddmStructureFieldName)) {
						ddmField.setValue(themeDisplay.getLocale(), ddmStructureFieldValue);
					}
					%>

					<liferay-ddm:html-field
						classNameId="<%= PortalUtil.getClassNameId(DDMStructure.class) %>"
						classPK="<%= field.getClassTypeId() %>"
						field="<%= ddmField %>"
						fieldsNamespace="<%= fieldsNamespace %>"
					/>
				</aui:form>
			</liferay-ui:search-container-column-text>

			<liferay-ui:search-container-column-text>
				<aui:button
					cssClass="selector-button"
					data='<%=
						HashMapBuilder.<String, Object>put(
							"fieldsnamespace", fieldsNamespace
						).put(
							"form", liferayPortletResponse.getNamespace() + field.getName() + "fieldForm"
						).put(
							"label", field.getLabel()
						).put(
							"name", field.getName()
						).put(
							"value",
							JSONUtil.put(
								"ddmStructureFieldName", ddmStructureFieldName
							).put(
								"ddmStructureFieldValue", ddmStructureFieldValue
							)
						).build()
					%>'
					disabled="<%= Objects.equals(field.getName(), ddmStructureFieldName) ? false : true %>"
					id='<%= "applyButton" + field.getName() %>'
					value="apply"
				/>
			</liferay-ui:search-container-column-text>
		</liferay-ui:search-container-row>

		<liferay-ui:search-iterator
			markupView="lexicon"
		/>
	</liferay-ui:search-container>
</clay:container-fluid>

<aui:script use="aui-base">
	A.on('domready', function (event) {
		A.all('.selector-button').each(function () {
			var selectorButton = this;

			var data = this.getData();

			var value = JSON.parse(data.value);

			var initialDDMForm = Liferay.component(
				'<portlet:namespace />' + data.fieldsnamespace + 'ddmForm'
			);

			initialDDMForm.get('fields').forEach(function (field) {
				if (field.get('name') === value.ddmStructureFieldName) {
					field.setValue(value.ddmStructureFieldValue);
				}
			});
		});
	});

	var Util = Liferay.Util;

	var structureFormContainer = A.one(
		'#<portlet:namespace />selectDDMStructureFieldForm'
	);

	var fieldSubtypeForms = structureFormContainer.all('form');

	var toggleDisabledFormFields = function (form, state) {
		Util.toggleDisabled(form.all('input, select, textarea'), state);
	};

	var submitForm = function (applyButton) {
		var result = Util.getAttributes(applyButton, 'data-');

		var fieldsnamespace = result.fieldsnamespace;

		var ddmForm = Liferay.component(
			'<portlet:namespace />' + fieldsnamespace + 'ddmForm'
		);

		ddmForm.updateDDMFormInputValue();

		var form = document.getElementById(result.form);

		Liferay.Util.fetch(form.action, {
			body: new FormData(form),
			method: 'POST',
		})
			.then(function (response) {
				return response.json();
			})
			.then(function (response) {
				var message = A.one('#<portlet:namespace />message');

				if (response.success) {
					result.className =
						'<%= editAssetListDisplayContext.getClassName(assetRendererFactory) %>';
					result.displayValue = response.displayValue;
					result.value = response.value;

					message.hide();

					Util.getOpener().Liferay.fire(
						'<%= HtmlUtil.escapeJS(eventName) %>',
						result
					);

					Util.getWindow().destroy();
				}
				else {
					message.show();
				}
			});
	};

	structureFormContainer.delegate(
		'click',
		function (event) {
			submitForm(event.currentTarget);
		},
		'.selector-button'
	);

	structureFormContainer.delegate(
		'submit',
		function (event) {
			var buttonId = event.currentTarget
				.one('#<portlet:namespace />buttonId')
				.attr('value');

			submitForm(structureFormContainer.one('#' + buttonId));
		},
		'form'
	);

	A.one('#<portlet:namespace />classTypeFieldsSearchContainer').delegate(
		'click',
		function (event) {
			var target = event.currentTarget;

			var buttonId = target.attr('data-button-id');
			var formId = target.attr('data-form-id');

			Util.toggleDisabled(
				structureFormContainer.all('.selector-button'),
				true
			);

			Util.toggleDisabled('#' + buttonId, false);

			toggleDisabledFormFields(fieldSubtypeForms, true);

			toggleDisabledFormFields(A.one('#' + formId), false);
		},
		'input[name=<portlet:namespace />selectStructureFieldSubtype]'
	);
</aui:script>