package com.bladecoder.ink.runtime.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.bladecoder.ink.runtime.Choice;
import com.bladecoder.ink.runtime.Story;

public class TestUtils {

	public static final String getJsonString(String filename) throws IOException {

		InputStream systemResourceAsStream = ClassLoader.getSystemResourceAsStream(filename);

		BufferedReader br = new BufferedReader(new InputStreamReader(systemResourceAsStream, "UTF-8"));

		try {
			StringBuilder sb = new StringBuilder();
			String line = br.readLine();

			while (line != null) {
				sb.append(line);
				sb.append("\n");
				line = br.readLine();
			}
			return sb.toString();
		} finally {
			br.close();
		}
	}

	public static final String runStory(String filename) throws Exception {
		// 1) Load story
		String json = TestUtils.getJsonString(filename).replace('\uFEFF', ' ');

		System.out.println(json);

		Story story = new Story(json);

		StringBuffer text = new StringBuffer();
		
		System.out.println(story.BuildStringOfHierarchy());

		// 2) Game content, line by line
		while (story.canContinue()) {
			String line = story.Continue();
			System.out.println(line);
			text.append(line);
			
			
			if (story.hasError()) {
                for (String errorMsg : story.getCurrentErrors()) {
                	System.out.println(errorMsg);
                }
            }

			// 3) Display story.currentChoices list, allow player to choose one
			if (story.getCurrentChoices().size() > 0) {

				for (Choice c : story.getCurrentChoices()) {
					System.out.println(c.gettext());
					text.append(c.gettext());
				}

				story.ChooseChoiceIndex((int) (Math.random() * story.getCurrentChoices().size()));
			}
		}

		return text.toString();
	}

}

@@ -1053,18 +1053,16 @@
 ffer();%0A
-%09%09
 %0A%09%09Syste
@@ -1109,16 +1109,89 @@
 hy());%0A%0A
+%09%09while (story.canContinue() %7C%7C story.getCurrentChoices().size() %3E 0) %7B%0A%09
 %09%09// 2) 
@@ -1217,16 +1217,17 @@
 by line%0A
+%09
 %09%09while 
@@ -1249,24 +1249,25 @@
 nue()) %7B%0A%09%09%09
+%09
 String line 
@@ -1282,24 +1282,25 @@
 Continue();%0A
+%09
 %09%09%09System.ou
@@ -1319,16 +1319,17 @@
 ne);%0A%09%09%09
+%09
 text.app
@@ -1342,20 +1342,18 @@
 ne);%0A%09%09%09
+%7D
 %0A
-%09%09%09
 %0A%09%09%09if (
@@ -1372,32 +1372,20 @@
 or()) %7B%0A
-                
+%09%09%09%09
 for (Str
@@ -1427,32 +1427,20 @@
 rs()) %7B%0A
-                
+%09%09%09%09
 %09System.
@@ -1466,38 +1466,17 @@
 g);%0A
-                %7D%0A            
+%09%09%09%09%7D%0A%09%09%09
 %7D%0A%0A%09

improve run story test loop.