package org.minager.core.utils;

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

public final class RegexUtils {

	private static final String EMAIL_REGEX = "^.*@.*\\..{2,}$";
	private static final String LOWER_LETTERS_REGEX = ".*[a-z].*";
	private static final String UPPER_LETTERS_REGEX = ".*[A-Z].*";
	private static final String NUMBER_REGEX = ".*[0-9].*";
	private static final String SPECIAL_CHAR_REGEX = ".*\\W.*";
	private static final String NUMBER_ONLY_REGEX = "^[0-9]+$";

	// La portée "package" permet à la classe StringUtils d'utiliser les patterns
	// suivants :
	static final Pattern EMAIL_PATTERN;
	static final Pattern LOWER_LETTERS_PATTERN;
	static final Pattern UPPER_LETTERS_PATTERN;
	static final Pattern NUMBER_PATTERN;
	static final Pattern SPECIAL_CHAR_PATTERN;
	static final Pattern NUMBER_ONLY_PATTERN;

	static {
		EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX);
		LOWER_LETTERS_PATTERN = Pattern.compile(LOWER_LETTERS_REGEX);
		UPPER_LETTERS_PATTERN = Pattern.compile(UPPER_LETTERS_REGEX);
		NUMBER_PATTERN = Pattern.compile(NUMBER_REGEX);
		SPECIAL_CHAR_PATTERN = Pattern.compile(SPECIAL_CHAR_REGEX);
		NUMBER_ONLY_PATTERN = Pattern.compile(NUMBER_ONLY_REGEX);
	}

	/**
	 * Chekcs if {@code pString} corresponds to an email address.
	 * 
	 * @param pString
	 *            The string which should be an email address.
	 * @return {@code true} if {@link pString} corresponds to an email address,
	 *         {@code false} otherwise.
	 */
	public static boolean isEmail(final String pString) {
		return EMAIL_PATTERN.matcher(pString).find();
	}

	/**
	 * Replace the sequences of {@code pString} matched by the {@code pRegex}
	 * with the {@code pReplacingString}.
	 * 
	 * @param pString
	 *            The string to update.
	 * @param pRegex
	 *            The regex to match the sentences to replace.
	 * @param pReplacingString
	 *            The string to replace the sentences which match with the
	 *            regex.
	 * @return The new string.
	 */
	public static String replaceSequence(final String pString,
			final String pRegex, final String pReplacingString) {
		return Pattern.compile(pRegex).matcher(pString)
				.replaceAll(pReplacingString);
	}
	
	/**
	 * Checks if {@code pString} corresponds to a number.
	 * 
	 * @param pString
	 *            The string which should be a number.
	 * @return {@code true} if {@code pString} corresponds to a number,
	 *         {@code false} otherwise.
	 */
	public static boolean isNumber(final String pString) {
		return NUMBER_ONLY_PATTERN.matcher(pString).find();
	}
	
	public static String getGroup(final String regex, final int numeroGroupe, final String chaine) {
		final Pattern pattern = Pattern.compile(regex);
		final Matcher matcher = pattern.matcher(chaine);
		matcher.find();
		return matcher.group(numeroGroupe);
	}
}