import { GenericService } from "../GenericService";
import mediaFileService from "./MediaFileService";
class MediaService extends GenericService {
  constructor() {
    super("/api/admin/media");
  }

  uploadMedia = (file) =>
    new Promise((resolve, reject) => {
      mediaFileService
        .getImageUploadUrl({ type: file.type, fileName: file.name })
        .then(async (res) => {
          console.log("RES URL: ", res, file);
          fetch(res.url, {
            method: "PUT",
            headers: {
              "Content-Type": file.type,
            },
            body: file,
          })
            .then((response) => {
              console.log("Res:", response, res.key);
              resolve(res.key);
            })
            .catch((err) => {
              console.log("Err in putting file on s3: ", err);
              reject(err);
            });
        })
        .catch((err) => {
          console.log("ERR in getting url: ", err);
          reject(err);
        });
    });

  uploadBase64Media = (base64Url, type, name) =>
    new Promise((resolve, reject) => {
      mediaFileService
        .getImageUploadUrl({ type: type, fileName: name })
        .then(async (res) => {
          function convertBase64ToFile(base64Url, fileName) {
            if (!/^data:image\/\w+;base64,/.test(base64Url)) {
              alert("Invalid base64 string");
              return;
            }

            // Decode the base64 string
            const binaryString = atob(base64Url.split(",")[1]);
            const byteArray = new Uint8Array(binaryString.length);

            for (let i = 0; i < binaryString.length; i++) {
              byteArray[i] = binaryString.charCodeAt(i);
            }

            const blob = new Blob([byteArray], {
              type: "application/octet-stream",
            });
            return blob;
          }
          let buffer = convertBase64ToFile(base64Url, name);
          // console.log("RES URL: ", res);
          // console.log("Blob: ", buffer);
          fetch(res.url, {
            method: "PUT",
            headers: {
              "Content-Type": type,
            },
            body: buffer,
          })
            .then((response) => {
              console.log("Res:", response, res.key);
              resolve(res.key);
            })
            .catch((err) => {
              console.log("Err in putting file on s3: ", err);
              reject(err);
            });
        })
        .catch((err) => {
          console.log("ERR in getting url: ", err);
          reject(err);
        });
    });
}

const mediaService = new MediaService();
export default mediaService;
