package com.mycompany;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.wicket.RequestCycle;
import org.apache.wicket.protocol.http.BufferedWebResponse;
import org.apache.wicket.request.target.coding.IndexedParamUrlCodingStrategy;
import org.apache.wicket.util.string.Strings;
import org.apache.wicket.util.value.ValueMap;

public abstract class LowercaseOnlyIndexedUrlEncodingStrategy extends IndexedParamUrlCodingStrategy {

	private final String _baseUrl;

	public LowercaseOnlyIndexedUrlEncodingStrategy(final String mountPath, final String baseUrl, final Class<?> bookmarkablePageClass) {
		super(mountPath, bookmarkablePageClass);

		if (baseUrl.endsWith("/") && !Strings.isEmpty(getMountPath())) {
			_baseUrl = baseUrl + getMountPath();

		} else if (!baseUrl.endsWith("/") && !Strings.isEmpty(getMountPath())) {
			_baseUrl = baseUrl + "/" + getMountPath();
		} else {
			if (baseUrl.endsWith("/")) {
				_baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
			} else {
				_baseUrl = baseUrl;
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	protected final ValueMap decodeParameters(final String urlFragment, final Map urlParameters) {

		final ValueMap map = super.decodeParameters(urlFragment, urlParameters);

		if (containsUpperCase(urlFragment)) {

			final BufferedWebResponse response = (BufferedWebResponse) RequestCycle.get()
					.getResponse();
			response.getHttpServletResponse().setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
			response.getHttpServletResponse().setHeader("Location", _baseUrl
					+ urlFragment.toLowerCase());
		}

		return onDecodeParameters(urlFragment, map);
	}

	protected ValueMap onDecodeParameters(final String urlFragment, final ValueMap params) {
		return params;
	}

	private static boolean containsUpperCase(final String string) {

		if (string == null || string.length() == 0) {
			return false;
		}

		boolean containsUpper = false;
		int i = 0;

		do {
			final char c = string.charAt(i);

			if (Character.isUpperCase(c)) {
				containsUpper = true;
			}
		} while (containsUpper == false && ++i < string.length());

		return containsUpper;
	}

	@Override
	protected String urlEncodePathComponent(final String string) {
		return super.urlEncodePathComponent(string).toLowerCase();
	}

}

