import {ApiResponse, DataProviderArgs, Processor} from '~/types/interfaces'
import BaseProcessor from '~/services/data/processor/baseProcessor'
import {QUERY_TYPE} from '~/types/enums'

class ImageProcessor extends BaseProcessor implements Processor {
  /**
   * @param {DataProviderArgs} args
   */
  public static support(args: DataProviderArgs): boolean {
    return args.type === QUERY_TYPE.IMAGE
  }

  /**
   * proccessing des data
   * @param {BlobPart[]} data
   */
  // eslint-disable-next-line require-await
  async process(payload: ApiResponse): Promise<any> {
    if(payload.data.size === 0) throw new Error('image not found')

    let blob = new Blob([payload.data as BlobPart], {type: 'image/jpeg'});
    return await this.blobToBase64(blob);
  }

  /**
   * Transforme un Blob en Base64
   * @param {Blob} blob
   */
  async blobToBase64(blob: Blob) {
    return new Promise((resolve, _) => {
      const reader = new FileReader();
      reader.onloadend = () => resolve(reader.result);
      reader.readAsDataURL(blob);
    });
  }
}

export default ImageProcessor
