<commit_before>package com.bladecoder.engine.ink;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;

import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.Serializable;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.reflect.ReflectionException;
import com.bladecoder.engine.actions.Action;
import com.bladecoder.engine.actions.ActionCallback;
import com.bladecoder.engine.actions.ActionCallbackQueue;
import com.bladecoder.engine.actions.ActionFactory;
import com.bladecoder.engine.assets.EngineAssetManager;
import com.bladecoder.engine.i18n.I18N;
import com.bladecoder.engine.model.Text.Type;
import com.bladecoder.engine.model.VerbRunner;
import com.bladecoder.engine.model.World;
import com.bladecoder.engine.util.ActionCallbackSerialization;
import com.bladecoder.engine.util.ActionUtils;
import com.bladecoder.engine.util.EngineLogger;
import com.bladecoder.ink.runtime.Choice;
import com.bladecoder.ink.runtime.InkList;
import com.bladecoder.ink.runtime.ListDefinition;
import com.bladecoder.ink.runtime.Story;

public class InkManager implements VerbRunner, Serializable {
	public final static char NAME_VALUE_TAG_SEPARATOR = ':';
	public final static char NAME_VALUE_PARAM_SEPARATOR = '=';
	private final static String PARAM_SEPARATOR = ",";
	public final static char COMMAND_MARK = '>';

	private static ResourceBundle i18n;

	private Story story = null;
	private ExternalFunctions externalFunctions;

	private ActionCallback cb;

	// Depending on the reading order of Inventory, InkManager and Actor verbs,
	// the verbCallbacks may not exist. So, we search the Cb lazily when needed.
	private String sCb;

	private ArrayList<Action> actions;

	private boolean wasInCutmode;

	private String storyName;

	private int ip = -1;

	public InkManager() {
		externalFunctions = new ExternalFunctions();
		actions = new ArrayList<Action>();
	}

	public void newStory(InputStream is) throws Exception {

		String json = getJsonString(is);
		story = new Story(json);

		externalFunctions.bindExternalFunctions(this);
	}

	public void newStory(final String name) throws Exception {
		new Thread() {
			@Override
			public void run() {
				loadStory(name, null);
			}
		}.start();
	}

	synchronized private void loadStory(String name, String stateString) {
		FileHandle asset = EngineAssetManager.getInstance()
				.getAsset(EngineAssetManager.MODEL_DIR + name + EngineAssetManager.INK_EXT);

		try {
			long initTime = System.currentTimeMillis();
			newStory(asset.read());

			storyName = name;

			loadI18NBundle();

			EngineLogger.debug("INK STORY LOADING TIME (ms): " + (System.currentTimeMillis() - initTime));

			if (stateString != null) {
				initTime = System.currentTimeMillis();
				story.getState().loadJson(stateString);
				EngineLogger.debug("INK SAVED STATE LOADING TIME (ms): " + (System.currentTimeMillis() - initTime));
			}

		} catch (Exception e) {
			EngineLogger.error("Cannot load Ink Story: " + name + " " + e.getMessage());
			story = null;
			storyName = null;
		}
	}

	public void loadI18NBundle() {
		if (storyName != null && EngineAssetManager.getInstance().getModelFile(storyName + "-ink.properties").exists())
			i18n = I18N.getBundle(EngineAssetManager.MODEL_DIR + storyName + "-ink", true);
	}

	public String translateLine(String line) {
		if (line.charAt(0) == I18N.PREFIX) {
			String key = line.substring(1);

			// In ink, several keys can be included in the same line.
			String[] keys = key.split("@");

			String translated = "";

			for (String k : keys) {
				try {
					translated += i18n.getString(k);
				} catch (Exception e) {
					EngineLogger.error("MISSING TRANSLATION KEY: " + key);
					return key;
				}
			}

			return translated;
		}

		return line;
	}

	public String getVariable(String name) {
		return story.getVariablesState().get(name).toString();
	}

	public boolean compareVariable(String name, String value) {
		if (story.getVariablesState().get(name) instanceof InkList) {
			return ((InkList) story.getVariablesState().get(name)).ContainsItemNamed(value);
		} else {
			return story.getVariablesState().get(name).toString().equals(value);
		}
	}

	public void setVariable(String name, String value) throws Exception {
		if (story.getVariablesState().get(name) instanceof InkList) {

			InkList rawList = (InkList) story.getVariablesState().get(name);

			if (rawList.getOrigins() == null) {
				List<String> names = rawList.getOriginNames();
				if (names != null) {
					ArrayList<ListDefinition> origins = new ArrayList<ListDefinition>();
					for (String n : names) {
						ListDefinition def = story.getListDefinitions().getDefinition(n);
						if (!origins.contains(def))
							origins.add(def);
					}
					rawList.setOrigins(origins);
				}
			}

			rawList.addItem(value);
		} else
			story.getVariablesState().set(name, value);
	}

	private void continueMaximally() {
		String line = null;
		actions.clear();

		HashMap<String, String> currentLineParams = new HashMap<String, String>();

		while (story.canContinue()) {
			try {<commit_msg>Fix racing condition bug loading Ink story while setting variable.<commit_after>package com.bladecoder.engine.ink;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;

import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.Serializable;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.reflect.ReflectionException;
import com.bladecoder.engine.actions.Action;
import com.bladecoder.engine.actions.ActionCallback;
import com.bladecoder.engine.actions.ActionCallbackQueue;
import com.bladecoder.engine.actions.ActionFactory;
import com.bladecoder.engine.assets.EngineAssetManager;
import com.bladecoder.engine.i18n.I18N;
import com.bladecoder.engine.model.Text.Type;
import com.bladecoder.engine.model.VerbRunner;
import com.bladecoder.engine.model.World;
import com.bladecoder.engine.util.ActionCallbackSerialization;
import com.bladecoder.engine.util.ActionUtils;
import com.bladecoder.engine.util.EngineLogger;
import com.bladecoder.ink.runtime.Choice;
import com.bladecoder.ink.runtime.InkList;
import com.bladecoder.ink.runtime.ListDefinition;
import com.bladecoder.ink.runtime.Story;

public class InkManager implements VerbRunner, Serializable {
	public final static char NAME_VALUE_TAG_SEPARATOR = ':';
	public final static char NAME_VALUE_PARAM_SEPARATOR = '=';
	private final static String PARAM_SEPARATOR = ",";
	public final static char COMMAND_MARK = '>';

	private static ResourceBundle i18n;

	private Story story = null;
	private ExternalFunctions externalFunctions;

	private ActionCallback cb;

	// Depending on the reading order of Inventory, InkManager and Actor verbs,
	// the verbCallbacks may not exist. So, we search the Cb lazily when needed.
	private String sCb;

	private ArrayList<Action> actions;

	private boolean wasInCutmode;

	private String storyName;

	private int ip = -1;

	public InkManager() {
		externalFunctions = new ExternalFunctions();
		actions = new ArrayList<Action>();
	}

	public void newStory(InputStream is) throws Exception {

		String json = getJsonString(is);
		story = new Story(json);

		externalFunctions.bindExternalFunctions(this);
	}

	public void newStory(final String name) throws Exception {
		new Thread() {
			@Override
			public void run() {
				loadStory(name, null);
			}
		}.start();
	}

	synchronized private void loadStory(String name, String stateString) {
		FileHandle asset = EngineAssetManager.getInstance()
				.getAsset(EngineAssetManager.MODEL_DIR + name + EngineAssetManager.INK_EXT);

		try {
			long initTime = System.currentTimeMillis();
			newStory(asset.read());

			storyName = name;

			loadI18NBundle();

			EngineLogger.debug("INK STORY LOADING TIME (ms): " + (System.currentTimeMillis() - initTime));

			if (stateString != null) {
				initTime = System.currentTimeMillis();
				story.getState().loadJson(stateString);
				EngineLogger.debug("INK SAVED STATE LOADING TIME (ms): " + (System.currentTimeMillis() - initTime));
			}

		} catch (Exception e) {
			EngineLogger.error("Cannot load Ink Story: " + name + " " + e.getMessage());
			story = null;
			storyName = null;
		}
	}

	public void loadI18NBundle() {
		if (storyName != null && EngineAssetManager.getInstance().getModelFile(storyName + "-ink.properties").exists())
			i18n = I18N.getBundle(EngineAssetManager.MODEL_DIR + storyName + "-ink", true);
	}

	public String translateLine(String line) {
		if (line.charAt(0) == I18N.PREFIX) {
			String key = line.substring(1);

			// In ink, several keys can be included in the same line.
			String[] keys = key.split("@");

			String translated = "";

			for (String k : keys) {
				try {
					translated += i18n.getString(k);
				} catch (Exception e) {
					EngineLogger.error("MISSING TRANSLATION KEY: " + key);
					return key;
				}
			}

			return translated;
		}

		return line;
	}

	public String getVariable(String name) {
		return story.getVariablesState().get(name).toString();
	}

	public boolean compareVariable(String name, String value) {
		if (story.getVariablesState().get(name) instanceof InkList) {
			return ((InkList) story.getVariablesState().get(name)).ContainsItemNamed(value);
		} else {
			return story.getVariablesState().get(name).toString().equals(value);
		}
	}

	public synchronized void setVariable(String name, String value) throws Exception {
		if (story.getVariablesState().get(name) instanceof InkList) {

			InkList rawList = (InkList) story.getVariablesState().get(name);

			if (rawList.getOrigins() == null) {
				List<String> names = rawList.getOriginNames();
				if (names != null) {
					ArrayList<ListDefinition> origins = new ArrayList<ListDefinition>();
					for (String n : names) {
						ListDefinition def = story.getListDefinitions().getDefinition(n);
						if (!origins.contains(def))
							origins.add(def);
					}
					rawList.setOrigins(origins);
				}
			}

			rawList.addItem(value);
		} else
			story.getVariablesState().set(name, value);
	}

	private void continueMaximally() {
		String line = null;
		actions.clear();

		HashMap<String, String> currentLineParams = new HashMap<String, String>();

		while (story.canContinue()) {
			try {
{'fraction_non_alphanumeric': 0.11706906232453677, 'fraction_numerical': 0.0039303761931499155, 'mean_word_length': 4.452551020408163, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '675115', 'n_tokens_mistral': 3720, 'n_tokens_neox': 3271, 'n_words': 760}