var __rest = (this && this.__rest) || function (s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
    t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
import { updateTemplate } from './publish.utils';
import { upload } from './storage.utils';
export const publishOverview = async ({ dataId, storageUpload, publishData }) => {
  const template = await htmlTemplate();
  const { photo_url } = publishData, data = __rest(publishData, ["photo_url"]);
  let html = updateTemplate({ template, data });
  html = updatePhotoUrl({ html, photo_url });
  html = await updateList({ dataId, template: html, publishData, storageUpload });
  const { actor } = storageUpload;
  await uploadOverviewIC({ html, actor });
};
const htmlTemplate = async () => {
  const htmlTemplate = await fetch('https://raw.githubusercontent.com/deckgo/ic-kit/main/dist/index.html');
  return htmlTemplate.text();
};
const updatePhotoUrl = ({ photo_url, html }) => {
  if (!photo_url) {
    return html;
  }
  return html.replace('<!-- DECKDECKGO_PHOTO_URL -->', `<img role="presentation" alt="" loading="lazy" src="${photo_url}" />`);
};
const updateList = async ({ dataId, template, storageUpload, publishData }) => {
  const { title } = publishData;
  const { fullUrl } = storageUpload;
  const li = `<li data-id="${dataId}"><a href="${fullUrl}">${title}</a></li>`;
  const source = await htmlSource(storageUpload);
  if (!source) {
    return template.replace(/<!-- DECKDECKGO_DATA -->/, `${li}`);
  }
  const matches = [...source.matchAll(/<li\x20.*?data-id=".*?".*?li>/gm)];
  if (!matches || matches.length <= 0) {
    return template.replace(/<!-- DECKDECKGO_DATA -->/, `${li}`);
  }
  const list = matches.map((match) => match[0]);
  const index = list.indexOf(li);
  if (index > -1) {
    return template.replace(/<!-- DECKDECKGO_DATA -->/, list.map((entry, i) => (i === index ? li : entry)).join(''));
  }
  return template.replace(/<!-- DECKDECKGO_DATA -->/, [li, ...list].join(''));
};
const htmlSource = async ({ bucketUrl }) => {
  const response = await fetch(bucketUrl);
  if (response.ok) {
    return response.text();
  }
  return undefined;
};
const uploadOverviewIC = async ({ html, actor }) => {
  await upload({
    data: new Blob([html], { type: 'text/html' }),
    filename: 'index.html',
    folder: 'resources',
    storageActor: actor,
    headers: [['Cache-Control', 'max-age=0']],
    fullPath: '/'
  });
};
