/*
 * Functions operating on the Process table
 */

import {
	TableType,
} from "qrc:/js/lib/generated/enum";
import {
	getTable,
} from "./table_utils";

/**
 * Get all available process types
 */
export function getProcessTypes(): ProcessType[] {
	return getTable(TableType.process)
		.map(t => t.type);
}

/**
 * Get all active process types
 */
export function getActiveProcessTypes(): ProcessType[] {
	return getTable(TableType.process)
		.filter(t => t.active)
		.map(t => t.type);
}

/**
 * Note: this function must conform to DocumentGraphHandler's script API
 */
export function lookUpProcessType(processId: string, table?: readonly Readonly<Process>[]): ProcessType|undefined {
	table = table === undefined ? getTable(TableType.process) : table;
	const process = table.find(element => element.identifier === processId);
	if (process === undefined) {
		return undefined;
	}
	return process.type;
}

/**
 * @param processId Checked process-id
 * @param parentProcessId Id of parent-process
 * @param processTable Process table (optional - will be queried via API if unset)
 * @returns True if `processId` is a direct or indirect child process of `parentProcessId`
 */
export function isChildProcess(processId: string, parentProcessId: string, processTable?: readonly Readonly<Process>[]): boolean {
	processTable = processTable === undefined ? getTable(TableType.process) : processTable;
	const process = processTable.find(p => p.identifier === processId);
	if (process === undefined) {
		return wsi4.throwError("Process table inconsistent");
	}
	return process.parentIdentifier === parentProcessId ? true : process.parentIdentifier === "" ? false : isChildProcess(process.parentIdentifier, parentProcessId, processTable);
}

export function collectChildProcesses(parentProcessId: string) : string[] {
	return getTable(TableType.process)
		.filter((process, _index, self) => isChildProcess(process.identifier, parentProcessId, self))
		.map(process => process.identifier);
}
