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

export async function replaceText(
	id: string,
	currentText: string,
	newText: string,
	destPageIndices?: PdfPageSelection
): Promise<void> {
	const client: IronPdfServiceClient = await Access.ensureConnection();

	const pi = await AsyncPdfPageSelectionToIndexes(id, destPageIndices);

	return new Promise(
		(resolve: () => void, reject: (errorMsg: string) => void) => {
			pi.forEach((pageIndex) => {
				client.pdfiumTextReplaceText(
					{
						document: { documentId: id },
						currentText: currentText,
						newText: newText,
						pageIndex: pageIndex,
					},
					(err, value) => {
						if (err) {
							reject(`${err.name}/n${err.message}`);
						} else if (value) {
							handleEmptyResultP__Output(value, reject);
							resolve();
						}
					}
				);
			});
		}
	);
}

export async function extractAllText(
	id: string,
	destPageIndices?: PdfPageSelection
): Promise<string> {
	const client: IronPdfServiceClient = await Access.ensureConnection();
	const pi = await AsyncPdfPageSelectionToIndexes(id, destPageIndices);
	return new Promise(
		(resolve: (_: string) => void, reject: (errorMsg: string) => void) => {
			client.pdfiumTextExtractAllText(
				{
					document: { documentId: id },
					pageIndexes: pi,
				},
				(err, value) => {
					if (err) {
						reject(`${err.name}/n${err.message}`);
					} else if (value) {
						if (value?.exception) {
							handleRemoteException(value.exception, reject);
						}
						resolve(value.result ?? "");
					}
				}
			);
		}
	);
}
