/*
 * 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 net.morilib.sed.SedPatternEngine;
import net.morilib.sed.SedSubstituteFlags;
import net.morilib.unix.regex.BasicMatcher;
import net.morilib.unix.regex.BasicPattern;

public class SedBasicRegexEngine implements SedPatternEngine {

	private static final SedPatternEngine INSTANCE =
		new SedBasicRegexEngine();

	private SedBasicRegexEngine() {}

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

	public boolean matches(String pattern, String s, boolean ci,
			boolean am) {
		BasicPattern p;
		BasicMatcher m;

		p = BasicPattern.compile(
				pattern, ci ? BasicPattern.CASE_INSENSITIVE : 0);
		m = p.matcher(s);
		return am ? m.matchesAll() : m.matches();
	}

	public String replace(String pattern, String source,
			String replace, SedSubstituteFlags flags) {
		BasicPattern p;
		BasicMatcher m;
		int fl = 0, pn = 1;

		if(flags.isAllmatch())  fl |= BasicPattern.ALL_MATCH;
		if(flags.isCaseInsensitive()) {
			fl |= BasicPattern.CASE_INSENSITIVE;
		}

		if(flags.isGlobal()) {
			pn = -1;
		} else if(flags.getNumber() > 0) {
			pn = flags.getNumber();
		}

		p = BasicPattern.compile(pattern, fl);
		if((m = p.matcher(source)).matches()) {
			return m.replace(replace, pn);
		} else {
			return null;
		}
	}

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

}
