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

package com.liferay.portal.search.web.internal.search.bar.portlet;

import com.liferay.petra.string.StringPool;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.util.GetterUtil;

import java.util.Optional;

import javax.portlet.PortletPreferences;

/**
 * @author André de Oliveira
 */
public class SearchBarPortletDestinationUtil {

	public static boolean isSameDestination(
		PortletPreferences portletPreferences, ThemeDisplay themeDisplay) {

		String destination = GetterUtil.getString(
			portletPreferences.getValue("destination", StringPool.BLANK));

		if (isSameDestination(
				destination,
				themeDisplay.getLayoutFriendlyURL(themeDisplay.getLayout()))) {

			return true;
		}

		return false;
	}

	public static boolean isSameDestination(
		SearchBarPortletPreferences searchBarPortletPreferences,
		ThemeDisplay themeDisplay) {

		Optional<String> optional =
			searchBarPortletPreferences.getDestination();

		if (!optional.isPresent()) {
			return true;
		}

		if (isSameDestination(
				optional.get(),
				themeDisplay.getLayoutFriendlyURL(themeDisplay.getLayout()))) {

			return true;
		}

		return false;
	}

	protected static boolean isSameDestination(
		String destination, String friendlyURL) {

		int offset = 0;

		if (destination.charAt(0) != '/') {
			offset = 1;
		}

		if (destination.regionMatches(
				0, friendlyURL, offset, friendlyURL.length() - offset)) {

			return true;
		}

		return false;
	}

}