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

import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/06/02
 */
public class IntTrie {

	/**
	 * 
	 */
	public static IntTrie DEAD = new IntTrie(null);

	//
	Map<Integer, IntTrie> edges;
	IntTrie parent;
	boolean accept = false;
	int moji;

	//
	private IntTrie(Map<Integer, IntTrie> e) {
		this.edges = e;
	}

	//
	IntTrie() {
		this.edges = new HashMap<Integer, IntTrie>();
	}

	/**
	 * 
	 * @param c
	 * @return
	 */
	public IntTrie go(int c) {
		return edges.containsKey(c) ? edges.get(c) : DEAD;
	}

	/**
	 * 
	 * @param c
	 * @return
	 */
	public boolean contains(int c) {
		return edges.containsKey(c);
	}

	/**
	 * 
	 * @return
	 */
	public boolean isDead() {
		return edges == null || edges.isEmpty();
	}

	/**
	 * 
	 * @return
	 */
	public boolean isAccepted() {
		return accept;
	}

	/**
	 * 
	 * @return
	 */
	public String getKeyword() {
		final StringBuffer b = new StringBuffer();

		for(IntTrie x = this; x.parent != null; x = x.parent) {
			b.append((char)x.moji);
		}
		return b.reverse().toString();
	}

}
