import {EnumPixelFormat} from "./EnumPixelFormat";
import {NativeModules} from "react-native";
import {ImageEditorView} from "../dce";
import {ImageManager} from "../utility";
import {IntermediateResultManager} from "../cvr";

declare global {
  function imageDataToBase64(imageData: ImageData): string; //Installed in ImageSourceAdapterModule
}

/**
 * The ImageData interface represents image data, which contains the image bytes, width, height, stride, pixel format, orientation and a tag.
 * <p>
 * `Please release the imageData object when it is no longer needed. see` {@link ImageData.release}.
 *
 * If you want to display imagedata on react UI Element, you can use  {@link imageDataToBase64}
 * @see {@link imageDataToBase64}
 * @see {@link ImageEditorView.setOriginalImage}
 * @see {@link ImageManager.saveToFile}
 * */
export interface ImageData {
  /**
   * The raw bytes of the image, of type {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer ArrayBuffer}.
   * */
  buffer: ArrayBuffer;

  /**
   * The width of the image in pixels.
   * */
  width: number;

  /**
   * The height of the image in pixels.
   * */
  height: number;

  /**
   * The stride (or row width) of the image in bytes.
   * */
  stride: number;

  /**
   * The pixel format of the image, of type {@link EnumPixelFormat}
   * */
  format: EnumPixelFormat | number;

  /**
   * The orientation information of the image.
   * */
  orientation: number;

  /**
   * Release the native memory. Data cannot be used after release.
   * */
  release(): void;
}

// @ts-ignore Check whether __turboModuleProxy exists, it may not
const isTurboModuleEnabled = global.__turboModuleProxy != null;

const ISAModule = isTurboModuleEnabled ?
  require("./NativeDynamsoftImageSourceAdapterModule").default :
  NativeModules.DynamsoftImageSourceAdapterModule

let isInstalled = false
const installMethods = () => {
  if (!isInstalled) {
    ISAModule.install()
    isInstalled = true
  }
}


/**
 * Converts an ImageData object to a Base64-encoded string.
 *
 * @param {ImageData} imageData - The ImageData object to convert.
 * @returns {string} - The Base64-encoded string representation of the image data.
 * @see {@link IntermediateResultManager.getOriginalImage}
 */
export function imageDataToBase64(imageData: ImageData): string | undefined | null {
  installMethods();
  if (typeof global.imageDataToBase64 !== 'function') {
    return null;
  }
  return global.imageDataToBase64(imageData);
}
