import { DeepPartial, ImageRef } from '../core';
import { ImageInput, ResultWrapper, SerializedImageInput } from './customTypes';
import { createSBError } from './errors';

/**
 * @internal
 * @hidden
 */
export function mapRTUUIResult<T>(
  result: ResultWrapper<DeepPartial<T>>,
  LClass: new (source: DeepPartial<T>) => T
): ResultWrapper<T> {
  if (result.status === 'OK') {
    return {
      ...result,
      data: new LClass(result.data),
    };
  } else {
    return result;
  }
}

/**
 * @internal
 * @hidden
 */
export function handleImageInput(image: ImageInput): SerializedImageInput;
export function handleImageInput(image: ImageInput[]): SerializedImageInput[];
export function handleImageInput(
  image: ImageInput | ImageInput[]
): SerializedImageInput | SerializedImageInput[] {
  const handleInput = (input: ImageInput): SerializedImageInput => {
    if (input instanceof ImageRef) {
      return input.uniqueId ? { uniqueId: input.uniqueId } : { buffer: input.buffer };
    } else {
      return { imageFileUri: input };
    }
  };

  return Array.isArray(image) ? image.map(handleInput) : handleInput(image);
}

/**
 * @internal
 * @hidden
 */
export async function withSBErrorHandling<T>(fn: () => Promise<T>): Promise<T> {
  try {
    return await fn();
  } catch (error: any) {
    throw createSBError(error);
  }
}
