import b64ToBlob from 'b64-to-blob';
import { apiShopeeSeller } from './seller/init';

const base64ImageToBlob = (base64) => {
  return b64ToBlob(base64, 'image/png');
};

/**
 *
 * @param {Blob} blobImage
 * @returns {Promise<string>}
 */
export const uploadImageBloob = async (blobImage) => {
  const payload = new FormData();
  payload.append('file', blobImage);

  const result = await apiShopeeSeller.post('api/v3/general/upload_image/', payload, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });

  return result.data.resource_id;
};

/**
 *
 * @param {string} base64Image
 * @returns {Promise<string>}
 */
export const uploadImageBas64 = async (base64Image) => {
  const blobImage = base64ImageToBlob(base64Image);

  return uploadImageBloob(blobImage);
};

/**
 *
 * @param {string} imageUrl
 * @returns
 */
export const getImageUrlData = async (imageUrl) => {
  let img = await fetch(imageUrl);
  img = await img.blob();
  const bitmap = await createImageBitmap(img);
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  canvas.width = bitmap.width;
  canvas.height = bitmap.height;
  ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height);

  return new Promise((resolve) => {
    canvas.toBlob((blob) => {
      resolve({
        base64: canvas.toDataURL('image/png'),
        blob,
      });
    });
  });
};
