export const updateDeckBackground = ({ deck, storageFile, imgSrc }) => {
  if (!storageFile || !imgSrc) {
    return Object.assign({}, deck);
  }
  return {
    id: deck.id,
    data: Object.assign(Object.assign({}, deck.data), { updated_at: new Date(), background: updateContentImgSrcAlt({ data: deck.data.background, imgSrc, storageFile }) })
  };
};
export const updateSlideImages = ({ slide, images }) => {
  if (!images) {
    return Object.assign({}, slide);
  }
  const validImages = images.filter(({ src, storageFile }) => src !== undefined && storageFile !== undefined);
  let { content } = slide.data;
  validImages.forEach(({ src, storageFile }) => {
    content = updateContentImgSrcAlt({ data: content, storageFile, imgSrc: src });
  });
  return {
    id: slide.id,
    data: Object.assign(Object.assign({}, slide.data), { updated_at: new Date(), content })
  };
};
export const updateParagraphImages = ({ paragraph, images }) => {
  if (!images) {
    return Object.assign({}, paragraph);
  }
  const validImages = images.filter(({ src, storageFile }) => src !== undefined && storageFile !== undefined);
  let { children, nodeName, attributes } = paragraph.data;
  // The paragraph itself might be an image
  if (nodeName === 'deckgo-lazy-img' && attributes) {
    validImages.forEach(({ src, storageFile }) => {
      attributes = updateAttributeImgSrc({ attributes, storageFile, imgSrc: src });
    });
  }
  children = children === null || children === void 0 ? void 0 : children.map((content) => {
    validImages.forEach(({ src, storageFile }) => {
      content = updateContentImgSrcAlt({ data: content, storageFile, imgSrc: src });
    });
    return content;
  });
  return {
    id: paragraph.id,
    data: Object.assign(Object.assign({}, paragraph.data), { updated_at: new Date(), children,
      attributes })
  };
};
export const updateSlideChart = ({ slide, chart }) => {
  if (!chart) {
    return Object.assign({}, slide);
  }
  const { src, storageFile } = chart;
  if (!src || !storageFile) {
    return Object.assign({}, slide);
  }
  const { attributes } = slide.data;
  if (!attributes) {
    return Object.assign({}, slide);
  }
  const { downloadUrl } = storageFile;
  return {
    id: slide.id,
    data: Object.assign(Object.assign({}, slide.data), { updated_at: new Date(), attributes: Object.assign(Object.assign({}, attributes), { src: downloadUrl }) })
  };
};
const updateContentImgSrcAlt = ({ data, storageFile, imgSrc }) => {
  const { downloadUrl, name } = storageFile;
  let updateData = data.replaceAll(`img-src="${imgSrc}"`, `img-src="${downloadUrl}"`);
  updateData = updateData.replaceAll(`img-alt="${imgSrc}"`, `img-alt="${name}"`);
  return updateData;
};
const updateAttributeImgSrc = ({ attributes, storageFile, imgSrc }) => {
  const { downloadUrl } = storageFile;
  return Object.keys(attributes).reduce((acc, key) => {
    acc[key] = attributes[key] === imgSrc ? downloadUrl : attributes[key];
    return acc;
  }, {});
};
