import { deckPublishData } from '@deckdeckgo/editor';
import { setData } from './data.utils';
import { initIndexHTML, initUpload, updateMetaData, uploadPublishFileIC } from './publish.utils';
import { uploadSocialImage } from './publish.social.utils';
export const publishDeck = async ({ deck: deckSource }) => {
  const { id, data } = deckSource;
  const { meta } = data;
  // 1. Init and fill HTML
  const indexHTML = await initDeckIndexHTML({ deck: deckSource });
  const { storageUpload, publishData } = await initUpload({ indexHTML, folder: 'p', meta });
  // 2. Update deck published meta
  const deckData = updateMetaData({ data, meta: data.meta, name: data.name, storageUpload });
  // 3. Update deck meta information
  const deck = await setData({ key: `/decks/${id}`, id, data: deckData });
  // 4. Upload
  await uploadPublishFileIC(storageUpload);
  // 5. Upload
  await uploadSocialImage({ storageUpload, publishData });
  // 6. Tells the snapshot the process is over
  emitDeckPublished(deck);
  return {
    storageUpload,
    publishData,
    deck
  };
};
const initDeckIndexHTML = async ({ deck }) => {
  const publishData = await deckPublishData({ deck });
  const { slides } = publishData;
  const updateTemplateContent = ({ attr, template }) => template.replace('<!-- DECKDECKGO_DECK -->', `<deckgo-deck id="slider" embedded="true" ${attr || ''}>${slides.join('')}</deckgo-deck>`);
  const { html } = await initIndexHTML({ publishData, updateTemplateContent, sourceFolder: 'p' });
  return {
    html,
    publishData
  };
};
const emitDeckPublished = (deck) => {
  const { id, data } = deck;
  const deployedDeck = {
    id,
    data: Object.assign(Object.assign({}, data), { deploy: {
        api: {
          status: 'successful',
          updated_at: new Date()
        }
      } })
  };
  const $event = new CustomEvent('deckPublished', { detail: deployedDeck });
  document.dispatchEvent($event);
};
