package jp.hasc.hasctool.ui.views.beanslist;

import java.util.regex.Pattern;

/**
 * @author iwasaki
 */
public class StringSearcher {
	public static final StringSearcher NULL_SEARCHER = new StringSearcher(null);;
	private Pattern pattern_ = null;
	private String searchString_ = null;
	
	public StringSearcher(String searchString){
		if (searchString==null || searchString.isEmpty()) return;
		searchString_ = searchString;
		if (searchString.startsWith("/")) {
			int lastIdx=searchString.lastIndexOf("/");
			if (lastIdx>=1) {
				int f=0;
				String flagsStr=searchString.substring(lastIdx+1);
				f|=flagsStr.indexOf('i')>=0 ? Pattern.CASE_INSENSITIVE : 0;
				pattern_ = Pattern.compile(searchString.substring(1,lastIdx),f);
			}
		}
	}
	
	public boolean matches(String str) {
		if (pattern_!=null) {
			return pattern_.matcher(str).find();
		}else if (searchString_!=null){
			return str.contains(searchString_);
		}else {
			return true; // 空文字は常にマッチ
		}
	}

	public boolean isEmpty() {
		return pattern_==null && searchString_==null;
	}
}
