import { templateService } from "services";
import { UnlayerClassicDesign } from "types/unlayer";

/**
 * Creates a classic template object
 *
 * @param {string} html The HTML of the template
 * @returns {UnlayerClassicDesign} The classic template object
 */
export const createClassicTemplate = (html: string): UnlayerClassicDesign => {
  return {
    classic: true,
    html,
  };
};

/**
 * Uploads the template thumbnail to S3 using a signed URL
 *
 * @param {Blob} file The file blob to upload
 * @returns {Promise<void>}
 */
export const uploadEmailThumbnail = async (file: Blob): Promise<string> => {
  const signedThumbnailUploadUrl =
    await templateService.getSignedThumbnailUploadUrl();
  // TODO: in the case of failure, what's the best course of action? For now, let's
  // continue, but we should probably throw.
  if (!signedThumbnailUploadUrl) return "";

  const options = {
    method: "PUT",
    body: file,
    headers: {
      "Content-Type": "image/png",
    },
  };

  const response = await fetch(signedThumbnailUploadUrl.signedUrl, options);
  if (!response.ok) {
    throw new Error("Failed to upload template thumbnail");
  }
  return response.url;
};

/**
 * Converts a data URI to a blob
 *
 * @param {string} dataUri The data URI to convert
 * @returns {Blob} The converted blob
 */
export const dataURItoBlob = (dataUri: string, mimetype: string) => {
  const binary = atob(dataUri.split(",")[1]);
  const array = [];

  for (let i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }

  return new Blob([new Uint8Array(array)], { type: mimetype });
};
