import firebase from 'firebase/app';
import { get } from 'idb-keyval';
import { docSelector } from '@deckdeckgo/editor';
import { uploadLocalImages } from './sync.storage.utils';
import { deleteParagraph, updateParagraph } from '../../providers/data/paragraph.firebase';
export const uploadParagraphs = ({ data, userId }) => {
  return new Promise(async (resolve, reject) => {
    if (!data || data.length <= 0) {
      resolve();
      return;
    }
    try {
      const promises = data.map(({ docId, paragraphId }) => uploadParagraph({ docId, paragraphId, userId }));
      await Promise.all(promises);
      resolve();
    }
    catch (err) {
      reject(err);
    }
  });
};
const uploadParagraph = async ({ docId, paragraphId, userId }) => {
  await uploadParagraphLocalUserAssets({ docId, paragraphId, userId });
  await uploadParagraphData(docId, paragraphId);
};
const uploadParagraphLocalUserAssets = ({ docId, paragraphId, userId }) => {
  return new Promise(async (resolve, reject) => {
    const paragraphElement = document.querySelector(`${docSelector} > article *[paragraph_id="${paragraphId}"]`);
    if (!paragraphElement) {
      resolve();
      return;
    }
    try {
      const updateContent = ({ data: paragraph, imgSrc, downloadUrl }) => {
        // The paragraph itself might be an image
        if (paragraph.data.nodeName === 'deckgo-lazy-img') {
          return {
            id: paragraph.id,
            data: Object.assign(Object.assign({}, paragraph.data), { attributes: Object.assign(Object.assign({}, (paragraph.data.attributes || {})), { 'img-src': downloadUrl, 'img-alt': downloadUrl }) })
          };
        }
        if (!paragraph.data.children) {
          return paragraph;
        }
        return {
          id: paragraph.id,
          data: Object.assign(Object.assign({}, paragraph.data), { children: paragraph.data.children.map((child) => {
              child = child.replace(`img-src="${imgSrc}"`, `img-src="${downloadUrl}"`);
              child = child.replace(`img-alt="${imgSrc}"`, `img-alt="${downloadUrl}"`);
              return child;
            }) })
        };
      };
      await uploadLocalImages({ element: paragraphElement, key: `/docs/${docId}/paragraphs/${paragraphId}`, userId, updateContent });
      resolve();
    }
    catch (err) {
      reject(err);
    }
  });
};
const uploadParagraphData = (docId, paragraphId) => {
  return new Promise(async (resolve, reject) => {
    var _a;
    try {
      const paragraph = await get(`/docs/${docId}/paragraphs/${paragraphId}`);
      if (!paragraph || !paragraph.data) {
        // If upload process end up in error in a previous try, some paragraphs might have already been uploaded correctly and remove from the local db
        resolve();
        return;
      }
      if (paragraph.data.children === null || ((_a = paragraph.data.children) === null || _a === void 0 ? void 0 : _a.length) <= 0) {
        // @ts-ignore
        paragraph.data.children = firebase.firestore.FieldValue.delete();
      }
      await updateParagraph(docId, paragraph);
      resolve();
    }
    catch (err) {
      reject(err);
    }
  });
};
export const deleteParagraphs = async (data) => {
  if (!data || data.length <= 0) {
    return;
  }
  const promises = data.map(({ docId, paragraphId }) => deleteParagraph(docId, paragraphId));
  await Promise.all(promises);
};
