import {
	WorkStepType,
} from "qrc:/js/lib/generated/enum";
import {
	assert,
	assertDebug,
} from "./utils";

/**
 * A "signature" WorkStepType defines the characteristics of an article
 *
 * A signature WorkStepType is deduced from the list of all `WorkStepType`s of an article.
 */
export function computeSignatureWst(articleWsts: readonly WorkStepType[]): WorkStepType {
	assertDebug(() => articleWsts.length > 0, "Pre-condition violated");

	// Prioritize `WorkStep`s so when sorting all nodes of an article the signature node is the left-most value.
	// As not all `WorkStepType`s can be part of the same article, the order is arbitrary to a certain degree.
	// Relevant WorkStepType relations are asserted below.
	// Two `WorkStepType`s are related if they can occur in the same article
	const wstPriorityMap: {[wst in WorkStepType]: number} = {
		sheetBending: 0,
		sheetCutting: 1,
		tubeCutting: 2,
		joining: 3,
		userDefinedBase: 4,
		sheet: 5,
		tube: 6,
		userDefined: 7,
		packaging: 8,
		transform: 9,
		undefined: 10,
	};

	if (wsi4.util.isDebug()) {
		assert(wstPriorityMap[WorkStepType.sheetBending] < wstPriorityMap[WorkStepType.sheetCutting], "sheetBending must dominate sheetCutting");
		assert(wstPriorityMap[WorkStepType.sheetCutting] < wstPriorityMap[WorkStepType.userDefined], "sheetCutting must dominate userDefined");
		assert(wstPriorityMap[WorkStepType.sheetCutting] < wstPriorityMap[WorkStepType.transform], "sheetBending must dominate transform");
		assert(wstPriorityMap[WorkStepType.sheetCutting] < wstPriorityMap[WorkStepType.packaging], "sheetBending must dominate packaging");
		assert(wstPriorityMap[WorkStepType.sheetCutting] < wstPriorityMap[WorkStepType.sheet], "sheetCutting must dominate sheet");
		assert(wstPriorityMap[WorkStepType.joining] < wstPriorityMap[WorkStepType.userDefined], "joining must dominate userDefined");
		assert(wstPriorityMap[WorkStepType.joining] < wstPriorityMap[WorkStepType.transform], "joining must dominate transform");
		assert(wstPriorityMap[WorkStepType.joining] < wstPriorityMap[WorkStepType.packaging], "joining must dominate packaging");
		assert(wstPriorityMap[WorkStepType.userDefinedBase] < wstPriorityMap[WorkStepType.userDefined], "userDefinedBase must dominate userDefined");
		assert(wstPriorityMap[WorkStepType.userDefinedBase] < wstPriorityMap[WorkStepType.transform], "userDefinedBase must dominate transform");
	}

	const signatureWst = articleWsts.map((wst): [ WorkStepType, number ] => [
		wst,
		wstPriorityMap[wst],
	])
		.sort((lhs, rhs) => lhs[1] - rhs[1])[0]![0];
	return signatureWst;
}

export function isSignatureWst(targetWst: WorkStepType, articleWsts: readonly WorkStepType[]): boolean {
	return computeSignatureWst(articleWsts) === targetWst;
}

