import { getIdentity } from '../auth/auth.ic';
import { internetIdentityAuth } from '../../utils/identity.utils';
import { syncDeckBackground, syncSlideChart, syncSlideImage } from '../../utils/sync.window.utils';
import { uploadWorker } from '../../workers/sync.ic.worker';
// - we cannot use postmessage because of CORS
// - we have to path the function separately for serialisation reason
const syncWindow = async ({ msg, data }) => {
  if (msg === 'deckdeckgo_sync_deck_background') {
    await syncDeckBackground(data);
  }
  if (msg === 'deckdeckgo_sync_slide_image') {
    await syncSlideImage(data);
  }
  if (msg === 'deckdeckgo_sync_slide_chart') {
    await syncSlideChart(data);
  }
};
export const sync = async ({ syncData, clean }) => {
  const identity = getIdentity();
  if (!identity) {
    throw new Error('No internet identity to sync data');
  }
  const internetIdentity = await internetIdentityAuth();
  await uploadWorker({
    internetIdentity,
    syncData,
    host: `${window.location}`
  }, syncWindow);
  await clean(syncData);
};
