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

import java.util.Set;

import net.morilib.automata.NFAState;
import net.morilib.automata.nfa.NFAs;

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/10/13
 */
public class NinaNFAMatcher implements NinaMatcher {

	//
	private NinaNFAPattern pattern;
	private Set<NFAState> etats;
	private String str;
	private String matched = null;

	//
	NinaNFAMatcher(NinaNFAPattern p, String s) {
		pattern = p;
		str = s;
		etats = pattern.getInitialStates();
	}

	/**
	 * 
	 * @return
	 */
	public boolean matches() {
		StringBuilder matches = new StringBuilder();
		Set<NFAState> t = etats;
		int a;

		for(int i = 0; i < str.length(); i++) {
			a = str.charAt(i);
			matches.appendCodePoint(a);
			t = NFAs.getStates(pattern.nfa, etats, a);
			etats = NFAs.getEpsilonReachable(pattern.nfa, t);
			if(etats.isEmpty())  return false;
		}

		if(pattern.nfa.isFinalAny(etats)) {
			matched = matches.toString();
			return true;
		} else {
			matched = null;
			return false;
		}
	}

	/**
	 * 
	 * @return
	 */
	public boolean lookingAt() {
		StringBuilder matches = new StringBuilder();
		Set<NFAState> t = etats;
		int a;

		for(int i = 0; i < str.length(); i++) {
			a = str.charAt(i);
			matches.appendCodePoint(a);
			t = NFAs.getStates(pattern.nfa, etats, a);
			etats = NFAs.getEpsilonReachable(pattern.nfa, t);
			if(etats.isEmpty()) {
				break;
			} else if(pattern.nfa.isFinalAny(etats)) {
				matched = matches.toString();
			}
		}
		return matched != null;
	}

	/**
	 * 
	 * @return
	 */
	public boolean find() {
		StringBuilder matches = new StringBuilder();
		Set<NFAState> t = etats;
		int a;

		for(int i = 0; i < str.length(); i++) {
			a = str.charAt(i);
			matches.appendCodePoint(a);
			t = NFAs.getStates(pattern.nfa, etats, a);
			etats = NFAs.getEpsilonReachable(pattern.nfa, t);
			if(etats.isEmpty()) {
				if(matched == null) {
					matches = new StringBuilder();
					reset();
				} else {
					break;
				}
			} else if(pattern.nfa.isFinalAny(etats)) {
				matched = matches.toString();
			}
		}
		return matched != null;
	}

	/**
	 * 
	 * @return
	 */
	public String group() {
		return matched;
	}

	/**
	 * 
	 */
	public void reset() {
		etats = pattern.getInitialStates();
		matched = null;
	}

}
