/*
 * Copyright 2013 Yuichiro Moriguchi
 *
 * 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 net.morilib.sed.pattern;

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

import net.morilib.sed.SedPatternEngine;
import net.morilib.sed.SedSubstituteFlags;


public class JavaStandardSedPatternEngine implements SedPatternEngine {

	private static final SedPatternEngine INSTANCE =
		new JavaStandardSedPatternEngine();

	private JavaStandardSedPatternEngine() {}

	/**
	 * 
	 * @return
	 */
	public static SedPatternEngine getInstance() {
		return INSTANCE;
	}

	public boolean matches(String pattern, String s, boolean ci,
			boolean am) {
		int fl = ci ? Pattern.CASE_INSENSITIVE : 0, c;
		Pattern p = Pattern.compile(pattern, fl);

		if(am) {
			return p.matcher(s).matches();
		} else {
			for(int i = 0; i < s.length(); i += c > 0xffff ? 2 : 1) {
				c = s.codePointAt(i);
				if(p.matcher(s.substring(i)).lookingAt()) {
					return true;
				}
			}
			return false;
		}
	}

	public String replace(String pattern, String source,
			String replace, SedSubstituteFlags flags) {
		Pattern p;
		Matcher m;
		String s;
		int fl = 0;

		if(flags.isCaseInsensitive()) {
			fl |= Pattern.CASE_INSENSITIVE;
		}

		p = Pattern.compile(pattern, fl);
		if((m = p.matcher(source)).matches()) {
			if(flags.isGlobal()) {
				s = m.replaceAll(replace);
			} else {
				s = m.replaceFirst(replace);
			}
			return s;
		} else {
			return null;
		}
	}

	public String toString() {
		return "Java standard regular expression";
	}

}
