package net.morilib.sh;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PushbackReader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;

import net.morilib.sh.builtin.ShBuiltInCommands;
import net.morilib.sh.misc.IOs;
import net.morilib.sh.misc.XtraceStream;

import junit.framework.TestCase;

public class ShSubstituteTest extends TestCase {

	static final ShRuntime T1 = new ShRuntime() {

		public int eval(ShEnvironment env,
				ShFileSystem fs,
				InputStream stdin,
				PrintStream stdout,
				PrintStream stderr,
				XtraceStream p,
				String script) {
			if(script.equals("whoami")) {
				stdout.print("haruka");
				stdout.flush();
			}
			return 0;
		}

	};

	static void eqs(String cmd, String... args) {
		try {
			ShLexer lex = new ShLexer(new PushbackReader(
					new StringReader(cmd)));
			ShTreeSimpleCommand c = ((ShTreeSimpleCommand)
					ShParser.parseCommand(lex, lex.nextToken()));
			List<String> a = Arrays.asList(args);
			ShEnvironment env = new ShRootShellEnvironment(new ShRootEnvStub()) {

				public List<String> getPath() {
					return Arrays.asList(new String[] {
							"/kotori", "/chihiro"
					});
				}

			};

			env.bind("VAR", "name");
			env.bind("VR2", "name  split");
			env.put("IFS", " ");
			assertEquals(a, c.substitute(
					env,
					ShBuiltInCommands.getInstance(),
					T1,
					new ShFileSystemStub(),
					ShReplaceTest.ERR_OUT,
					new XtraceStream(IOs.NULL_OUTPUT)));
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (ShSyntaxException e) {
			throw new RuntimeException(e);
		}
	}

	public void testSubstitute001() {
		eqs("ls -l", "ls", "-l");
	}

	public void testSubstitute002() {
		eqs("echo ${VAR}", "echo", "name");
	}

	public void testSubstitute003() {
		eqs("echo ${VR2}", "echo", "name", "split");
		eqs("echo aa${VR2}aa", "echo", "aaname", "splitaa");
	}

	public void testSubstitute004() {
		eqs("echo \"${VR2}\"", "echo", "name  split");
		eqs("echo aa\"${VR2}\"aa", "echo", "aaname  splitaa");
	}

	public void testSubstitute005() {
		eqs("echo '${VR2}'", "echo", "${VR2}");
		eqs("echo aa'${VR2}'aa", "echo", "aa${VR2}aa");
	}

	public void testSubstitute006() {
		eqs("echo /*a", "echo", "haruka", "chihaya", "azusa");
	}

	public void testSubstitute007() {
		eqs("echo '/*a'", "echo", "/*a");
		eqs("echo \"/*a\"", "echo", "/*a");
	}

	public void testSubstitute008() {
		eqs("ritsuko aaa", "//kotori/ritsuko", "aaa");
	}

	public void testSubstitute009() {
		eqs("echo /*aaa", "echo", "/*aaa");
	}

}
