import {
	TableType,
} from "qrc:/js/lib/generated/enum";
import {
	getSettingOrDefault,
} from "qrc:/js/lib/settings_table";
import {
	createUpdatedSharedData,
} from "qrc:/js/lib/shared_data";

import {
	run as runTableMigration,
} from "./table_migration";

export function populateSharedData(): void {
	let obj = wsi4.sharedData.read();
	{
		const mode = getSettingOrDefault("sheetNestingMode");
		if (mode !== "clientDecision") {
			const enabled = mode === "mixed";
			obj = createUpdatedSharedData("sheetMergingEnabled", enabled, obj);
		}
	}
	wsi4.sharedData.write(obj);
}

/**
 * Populate tables that are missing entirely.
 *
 * This makes separate table migrations obsolete if they are limited to
 * population of new tables with default values.
 *
 * This allows to ensure that for breaking changes each table will actually
 * be forked.  This would not be the case if e.g. a table (with empty default
 * table) would not be set at all.
 */
export function populateInternalTables() : void {
	Array.from(TableType)
		.filter(tableType => !wsi4.tables.isExternalTable(tableType) && !wsi4.tables.isInternalTable(tableType))
		.map(tableType => wsi4.tables.getDefault(tableType))
		.forEach(tableType => wsi4.tables.setInternalTable(tableType));
}

export function migrateInternalTables() : void {
	runTableMigration();
}
