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

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringReader;

import junit.framework.TestCase;

public class BcTest extends TestCase {

	void eqn(String s, String t) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		PrintStream ous = new PrintStream(bos);
		BcNamespace ns = new BcRootNamespace();
		BcParser p;

		try {
			p = new BcParser(System.in, ous);
			p.run(new StringReader(s), ns, -1);
			assertEquals(t, new String(bos.toByteArray()).replaceAll(
					"\r\n", "\n"));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public void testBc001() {
		eqn("1", "1\n");
		eqn("1+2", "3\n");
		eqn("a = 2; a", "2\n");
	}

	public void testBc002() {
		eqn("if(1 == 1) 2 else 3", "2\n");
		eqn("if(1 != 1) 2 else 3", "3\n");
		eqn("if(1 == 1) { 2; 3; } else { 3; 4; }", "2\n3\n");
		eqn("if(1 != 1) { 2; 3; } else { 3; 4; }", "3\n4\n");
	}

	public void testBc003() {
		eqn("print 1, \"aaa\"", "1aaa");
		eqn("print 1 + 2, \"aaa\"", "3aaa");
	}

	public void testBc004() {
		eqn("for(i = 0; i < 10; i++) i", "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n");
		eqn("for(i = 0; i < 10; ++i) i", "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n");
	}

	public void testBc005() {
		eqn("i = 0; while(i++ < 5) i", "1\n2\n3\n4\n5\n");
		eqn("i = 0; while(++i < 5) i", "1\n2\n3\n4\n");
	}

	public void testBc006() {
		eqn("for(i = 0; i < 5; i++) { if(i == 3)  break  else  i; }",
				"0\n1\n2\n");
		eqn("for(i = 0; i < 5; i++) { if(i == 3)  continue  else  i; }",
				"0\n1\n2\n4\n");
		eqn("for(i = 0; i < 5; i++) { if(i == 3)  halt  else  i; }",
				"0\n1\n2\n");
	}

	public void testBc007() {
		eqn(    "define fn1 (a, b) { return a + b; }\n" +
				"fn1(1, 2)",
				"3\n");
		eqn(    "define fn1 (a) { if(a == 2) return 0 else return 1; }\n" +
				"fn1(2)",
				"0\n");
		eqn(    "define fn1 (a) { if(a == 2) return 0 else return 1; }\n" +
				"fn1(1)",
				"1\n");
	}

	public void testBc008() {
		eqn("sqrt(841)", "29\n");
	}

}
