import { onMessage } from 'webext-bridge/content-script';
import { EVENT_TAB_GET_WEBCONTENT_HTML, EVENT_TAB_CREATE_BLOB_URL } from '@/bridge/config/event';

const base64ToFile = (base64, filename) => {
  const arr = base64.split(',');
  const mimeMatch = arr[0].match(/:(.*?);/);
  const mime = mimeMatch ? mimeMatch[1] : 'application/octet-stream';
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
};

const base64ToBlob = (base64, type) => {
  const file = base64ToFile(base64);
  const blob = new Blob([file], { type });
  const url = URL.createObjectURL(blob);

  return url;
};

onMessage(EVENT_TAB_GET_WEBCONTENT_HTML, () => {
  return document.documentElement.outerHTML;
});

onMessage(EVENT_TAB_CREATE_BLOB_URL, ({ data }) => {
  const { base64, type } = data;
  return base64ToBlob(base64, type);
});
