import { PdfPageSelection } from "../../../public/types";
import { IronPdfServiceClient } from "../../generated_proto/ironpdfengineproto/IronPdfService";
import { Access } from "../../access";
import {
	AsyncPdfPageSelectionToIndexes,
	handleEmptyResultP__Output,
} from "../util";

export async function addBackgroundForeground(
	destId: string,
	srcId: string,
	srcPageIndex: number,
	isBackground: boolean,
	destPageIndices?: PdfPageSelection
): Promise<void> {
	const client: IronPdfServiceClient = await Access.ensureConnection();

	const pi = await AsyncPdfPageSelectionToIndexes(destId, destPageIndices);

	return new Promise(
		(resolve: () => void, reject: (errorMsg: string) => void) => {
			client.pdfiumBackgroundForegroundAddBackgroundForeground(
				{
					destinationPdf: { documentId: destId },
					destPageIndices: pi,
					layerMode: { enumValue: isBackground ? 1 : 0 },
					sourcePdf: { documentId: srcId },
					srcPageIndex: srcPageIndex,
				},
				(err, value) => {
					if (err) {
						reject(`${err.name}/n${err.message}`);
					} else if (value) {
						handleEmptyResultP__Output(value, reject);
						resolve();
					}
				}
			);
		}
	);
}
