/*
 * 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 net.morilib.automata.DFAState;

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

	//
	private NinaDFAPattern pattern;
	private DFAState<Object, Object, Void> etat;
	private String str;
	private String matched = null;

	//
	NinaDFAMatcher(NinaDFAPattern p, String s) {
		pattern = p;
		str = s;
		etat = pattern.getInitialState();
	}

	/**
	 * 
	 * @return
	 */
	public boolean matches() {
		for(int i = 0; i < str.length(); i++) {
			etat = etat.goInt(str.charAt(i));
			if(i + 1 == str.length() && etat.isAccepted()) {
				matched = str;
				return true;
			} else if(etat.isDead()) {
				return false;
			}
		}
		return false;
	}

	/**
	 * 
	 * @return
	 */
	public boolean lookingAt() {
		StringBuilder matches = new StringBuilder();
		int a;

		for(int i = 0; i < str.length(); i++) {
			etat = etat.goInt(a = str.charAt(i));
			matches.appendCodePoint(a);
			if(etat.isAccepted()) {
				matched = matches.toString();
			}
			if(etat.isDead())  break;
		}
		return matched != null;
	}

	/**
	 * 
	 * @return
	 */
	public boolean find() {
		StringBuilder matches = new StringBuilder();
		int a;

		for(int i = 0; i < str.length(); i++) {
			etat = etat.goInt(a = str.charAt(i));
			matches.appendCodePoint(a);
			if(etat.isAccepted()) {
				matched = matches.toString();
			}

			if(!etat.isDead()) {
				// do nothing
			} else if(matched != null) {
				break;
			} else {
				reset();
				matches = new StringBuilder();
			}
		}
		return matched != null;
	}

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

	/**
	 * 
	 */
	public void reset() {
		etat = pattern.getInitialState();
		matched = null;
	}

}
