/**
 * License Agreement.
 *
 *  JBoss RichFaces - Ajax4jsf Component Library
 *
 * Copyright (C) 2007  Exadel, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

package org.richfaces.component.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import org.ajax4jsf.util.HtmlDimensions;

/**
 * @author Nick Belaevski - nbelaevski@exadel.com created 09.02.2007
 * 
 */
public class HtmlUtil {
	public static String qualifySize(String sizeDeclaration) {
		String trimmedValue = sizeDeclaration.trim();
		if (trimmedValue.length() != 0) {
			char lastChar = trimmedValue.charAt(trimmedValue.length() - 1);
			if (Character.isDigit(lastChar)) {
				return sizeDeclaration + "px";
			}
		}

		return sizeDeclaration;
	}

	public static String addToSize(String declaration, String delta) {
		Double doubleDelta = HtmlDimensions.decode(delta);
		Double decoded = HtmlDimensions.decode(declaration);

		return HtmlDimensions.formatPx(new Double(decoded.doubleValue()
				+ doubleDelta.doubleValue()));
	}

	public static final Pattern idSelectorPattern = Pattern
			.compile("#((:|_|[a-z,A-Z])[a-z,A-Z,0-9,_,-,:]+)");

	public static String expandIdSelector(String selector,
			UIComponent component, FacesContext context) {
		Matcher matcher = idSelectorPattern.matcher(selector);
		StringBuffer sb = new StringBuffer();

		while (matcher.find()) {
			if (matcher.group(1).indexOf("::") == -1) {
				// make new id selector here using matcher.group(1)

				UIComponent target = component.findComponent(matcher.group(1));

				if (target != null) {
					matcher.appendReplacement(sb, "#"
							+ target.getClientId(context).replaceAll(":", "\\\\\\\\\\\\\\\\:"));
				}
			}
		}
		matcher.appendTail(sb);
		String result = sb.toString();
		if (result.length() == 0)
			result = selector;
		return sb.toString();
	}
}
