import {
	isStringIndexedInterface,
} from "qrc:/js/lib/generated/typeguard";
import {
	isArray,
	parseJson,
} from "qrc:/js/lib/utils";

export function run(objsJson: string): void {
	const objs = parseJson(objsJson, (t: unknown): t is Array<StringIndexedInterface> => isArray(t, isStringIndexedInterface));
	if (objs === undefined) {
		return wsi4.throwError("Objects do not form array of StringIndexedInterface");
	}
	for (const obj of objs) {
		if (!isArray(obj["sections"], (t: unknown): t is string => typeof t === "string")) {
			return wsi4.throwError("sections not available");
		}
		if (typeof obj["key"] !== "string") {
			return wsi4.throwError("key not available");
		}
		if (obj["value"] === undefined) {
			return wsi4.throwError("value not available");
		}
		const settingsPrefix = obj["sections"].join("_");
		const settingsKey = settingsPrefix + "_" + obj["key"];
		const settingsValue = JSON.stringify(obj["value"]);
		wsi4.io.settings.write(settingsKey, settingsValue);
	}
}
