/**
 * Copyright 2005-2016 hdiv.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.hdiv.web.servlet.support;

import java.util.HashMap;
import java.util.Map;

import org.hdiv.context.RequestContextHolder;
import org.hdiv.dataComposer.IDataComposer;
import org.springframework.web.servlet.support.RequestDataValueProcessor;

/**
 * {@link RequestDataValueProcessor} implementation for Thymeleaf.
 * 
 * Method invocation order is different in Thymeleaf compared to Spring MVC.
 * <ol>
 * <li>processAction(..) method for form action</li>
 * <li>getExtraHiddenFields(..) method for extra hidden field</li>
 * <li>processFormFieldValue(..) method for each form field.</li>
 * </ol>
 */
public class ThymeleafHdivRequestDataValueProcessor extends HdivRequestDataValueProcessor {

	@Override
	public String processAction(final RequestContextHolder request, final String action, final String method) {

		IDataComposer dataComposer = request.getDataComposer();

		if (dataComposer != null && dataComposer.isRequestStarted()) {
			// End with the last form
			dataComposer.endRequest();
		}

		// Start with the new form
		return super.processAction(request, action, method);
	}

	@SuppressWarnings("deprecation")
	@Override
	public Map<String, String> getExtraHiddenFields(final RequestContextHolder ctx) {
		IDataComposer dataComposer = ctx.getDataComposer();
		Map<String, String> extraFields = new HashMap<String, String>();

		if (innerRequestDataValueProcessor != null) {
			Map<String, String> innerExtras = innerRequestDataValueProcessor.getExtraHiddenFields(ctx.getRequest());
			if (innerExtras != null) {
				extraFields.putAll(innerExtras);
			}
		}

		if (dataComposer == null || !dataComposer.isRequestStarted()) {
			return extraFields;
		}

		// Use the state id generated by the form action processing
		String formStateId = ctx.getFormStateId();

		if (formStateId != null && formStateId.length() > 0) {
			extraFields.put(dataComposer.getHdivParameterName(), formStateId);
		}
		return extraFields;
	}
}
