import { getIdentity } from '../auth/auth.ic';
import { createDeckBucketActor, createManagerActor } from '../../utils/deck.utils';
import { fromArray, fromTimestamp } from '../../utils/did.utils';
export const deckEntries = async (_userId) => {
  const identity = getIdentity();
  if (!identity) {
    return [];
  }
  const managerActor = await createManagerActor({ identity });
  console.log('Deck IC about to request entries');
  const buckets = await managerActor.entries();
  console.log('Deck IC entries done.', buckets);
  const promises = buckets.map((bucket) => getDeckIc({ bucket, identity }));
  const decksIc = await Promise.all(promises);
  console.log('Deck IC decks done.', decksIc);
  const decksPromises = decksIc === null || decksIc === void 0 ? void 0 : decksIc.filter((deck) => deck !== undefined).map((deck) => fromDeck({ deck, identity }));
  const decks = await Promise.all(decksPromises);
  return decks;
};
const getDeckIc = async ({ bucket, identity }) => {
  try {
    const deckBucket = await createDeckBucketActor({ identity, bucket });
    return await deckBucket.get();
  }
  catch (err) {
    console.error('Deck cannot be found.', bucket);
    return undefined;
  }
};
const fromDeck = async ({ deck, identity }) => {
  const data = await fromArray(deck.data);
  return {
    id: deck.deckId,
    data: Object.assign(Object.assign({}, data), { owner_id: identity.getPrincipal().toText(), created_at: fromTimestamp(deck.created_at), updated_at: fromTimestamp(deck.updated_at) })
  };
};
export const deleteDeck = async (deckId) => {
  if (!deckId) {
    return;
  }
  const identity = getIdentity();
  if (!identity) {
    return;
  }
  // We delete the all canister of the related deckId
  const managerActor = await createManagerActor({ identity });
  console.log('Deck IC about to delete deck and its slides');
  await managerActor.del(deckId);
  console.log('Deck IC delete');
};
