import { Skia, AlphaType, ColorType } from '@shopify/react-native-skia';
import { useResizePlugin } from 'vision-camera-resize-plugin';
import type {
  Crop,
  RotationDegree,
} from '../../../src/helpers/documentDetector';
import type { Frame } from 'react-native-vision-camera';

export function useCropToBase64(size: number) {
  const { resize } = useResizePlugin();

  return (frame: Frame, crop: Crop, rotation: RotationDegree) => {
    'worklet';

    const croppedForDebug = resize(frame, {
      rotation,
      pixelFormat: 'rgba',
      dataType: 'uint8',
      scale: {
        width: size,
        height: size,
      },
      crop,
    });
    const skiaImageInfo = {
      width: size,
      height: size,
      alphaType: AlphaType.Opaque,
      colorType: ColorType.RGBA_8888,
    };
    const skiaImageData = Skia.Data.fromBytes(croppedForDebug);
    const debugImage = Skia.Image.MakeImage(
      skiaImageInfo,
      skiaImageData,
      size * 4
    );
    return debugImage?.encodeToBase64();
  };
}
