import {
	showWarning,
} from "qrc:/js/lib/gui_utils";
import {
	isArray,
	isString,
	parseJson,
} from "qrc:/js/lib/utils";
import {
	getScriptArg,
} from "qrc:/js/lib/script_args";

import {
	isExternalInput,
} from "qrc:/js/lib/external_input";
import {
	FileHandlingResult,
	loadInputInGui,
	openFiles,
} from "./gui_io_filesystem";

// Import files specified in a json file with properties
export function run(): FileHandlingResult {
	if (wsi4.tables.findErrors().length > 0) {
		showWarning(wsi4.util.translate("tables_inconsistent_title"), wsi4.util.translate("tables_inconsistent_text."));
	}

	const jsonPath = getScriptArg("inputJsonPath");
	if (jsonPath !== undefined) {
		const buffer = wsi4.io.fs.readFile(jsonPath);
		if (buffer === undefined) {
			wsi4.util.error(`Cannot read JSON input from "${jsonPath}"`);
			return {
				success: false,
				path: "",
				graphUuid: wsi4.graph.currentUuid(),
			};
		}

		const json = wsi4.util.arrayBufferToString(buffer);
		const input = parseJson(json, isExternalInput);
		if (input === undefined) {
			wsi4.util.error("Input JSON invalid: " + json);
			return {
				success: false,
				path: "",
				graphUuid: wsi4.graph.currentUuid(),
			};
		}

		return loadInputInGui(input);
	} else {
		const positionalArguments = wsi4.sharedData.positionalArguments();
		if (!isArray(positionalArguments, isString) || positionalArguments.length === 0) {
			return {
				success: false,
				path: "",
				graphUuid: wsi4.graph.currentUuid(),
			};
		}
		return openFiles(positionalArguments);
	}
}
