export class FMPromise {
	private callbacksById = new Map<String, { resolve: (any), reject: (any) }>();

	private removePromiseWithId(promiseId: string) {
		const callback = this.callbacksById.get(promiseId);
		if (!callback) {
			throw new FMPromiseError({message: 'Unable to locate promise with id ' + promiseId});
		}
		this.callbacksById.delete(promiseId);
		return callback;
	}

	/**
	 * Private method called by FileMaker to provide a result for a script call.
	 */
	resolve(promiseId: string, result: string) {
		this.removePromiseWithId(promiseId).resolve(result);
		console.info(promiseId + ' Resolve with ' + result.length + ' chars');
	};

	/**
	 * Private method called by FileMaker to provide an error cause for a script call.
	 */
	reject(promiseId: string, errorString: string) {
		let errorObj;
		try {
			errorObj = JSON.parse(errorString);
		} catch (parseError) {
			console.warn('Unable to parse error response as JSON', errorString, parseError);
			errorObj = {message: errorString};
		}
		this.removePromiseWithId(promiseId).reject(errorObj);
		console.info(promiseId + ' Rejected:' + errorObj);
	}

	registerPromise(promiseId: string, callbacks: { resolve: any; reject: any }) {
		this.callbacksById.set(promiseId, callbacks);
	}
}
