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

import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

import net.morilib.sh.misc.XtraceStream;
import net.morilib.unix.glob.Wildcard;

public class ShPattern {

	private List<ShToken> patterns;

	/**
	 * 
	 * @param patterns
	 */
	public ShPattern(List<ShToken> patterns) {
		this.patterns = new ArrayList<ShToken>(patterns);
	}

	/**
	 * 
	 * @param env
	 * @param fs
	 * @param run
	 * @param s
	 * @return
	 * @throws IOException
	 * @throws ShSyntaxException
	 */
	public boolean matches(ShEnvironment env, ShFileSystem fs,
			ShRuntime run, PrintStream err, XtraceStream p,
			String s) throws IOException, ShSyntaxException {
		String v;

		for(ShToken t : patterns) {
			v = ShTrees.substituteCase(env, run, fs, err, p, t);
			if(Wildcard.matches(v, s))  return true;
		}
		return false;
	}

	public String toString() {
		StringBuffer b = new StringBuffer();
		String d = "";

		for(ShToken t : patterns) {
			b.append(d).append(t);
			d = "|";
		}
		return b.toString();
	}

}
