import {
	showWarning,
} from "qrc:/js/lib/gui_utils";
import {
	readCalcSettings,
} from "qrc:/js/lib/calc_settings";
import {
	getScriptArg,
} from "qrc:/js/lib/script_args";
import {
	getArticleName,
} from "qrc:/js/lib/graph_utils";

import {
	createGraphRepresentation,
	ScaleDataConfig,
} from "./export_graph_representation";

function exportToServer(serverUrl: string, graphJsonBa: ArrayBuffer) {
	const result = wsi4.io.net.http.post(serverUrl, "application/json", graphJsonBa);
	if (result.errorCode === 0) {
		wsi4.util.info(wsi4.util.translate("erp_export_successful") + ": " + serverUrl);
	} else {
		wsi4.util.error(wsi4.util.translate("erp_export_failed") + ": " + serverUrl + " (" + result.errorCode.toString() + ")");
	}
}

function exportToFile(filePath: string, graphJsonBa: ArrayBuffer) {
	const success = wsi4.io.fs.writeFile(filePath, graphJsonBa);
	if (success) {
		wsi4.util.info(wsi4.util.translate("erp_export_successful") + ": " + filePath);
	} else {
		wsi4.util.info(wsi4.util.translate("erp_export_failed") + ": " + filePath);
	}
}

export function run(): void {
	const config = getScriptArg("erpExportConfig");
	if (config === undefined) {
		return;
	}

	if (config.articleNameMaxLength !== undefined) {
		const limit = config.articleNameMaxLength;
		const invalidNames = wsi4.graph.articles()
			.map(article => getArticleName(article[0]!))
			.filter(n => n.length > limit)
			.slice(0, 20);
		if (invalidNames.length > 0) {
			showWarning(
				wsi4.util.translate("erp_export_name_length_exceeded_title"),
				wsi4.util.translate("max_length") + ": " + limit.toString() + "\n" +
					wsi4.util.translate("erp_export_name_length_exceeded_text") + ":\n\n" + invalidNames.join("\n"),
			);
			return;
		}
	}

	const graphJson = (() => {
		if (wsi4.isFeatureEnabled("graphRepExport")) {
			const scaleDataConfig: ScaleDataConfig = (() => {
				const calcSettings = readCalcSettings();
				switch (calcSettings.scaleValueMode) {
					case "none": return {
						type: "none",
					};
					case "relative": return {
						type: "relativeValues",
						values: calcSettings.baseScaleValues,
					};
					case "absolute": return {
						type: "absoluteValues",
						values: calcSettings.baseScaleValues,
					};
				}
			})();
			const graphRep = createGraphRepresentation(scaleDataConfig);
			return JSON.stringify(graphRep);
		} else {
			return wsi4.util.translate("graph_rep_export_is_liable_to_pay");
		}
	})();

	const graphJsonBa = wsi4.util.stringToArrayBuffer(graphJson);
	if (config.serverUrl !== undefined) {
		exportToServer(config.serverUrl, graphJsonBa);
	}
	if (config.filePath !== undefined) {
		exportToFile(config.filePath, graphJsonBa);
	}
}
