import { c as createActor, f as fromNullable, g as getIdentity, a as fromTimestamp, b as fromArray, d as createWorkerProxy, i as internetIdentityAuth } from './auth.ic-55cb31f4.js';
export { j as deleteAuth, k as deleteUser, g as getIdentity, e as initAuth, h as signIn, s as signOut, u as updateUser } from './auth.ic-55cb31f4.js';
import './index-5b83ee50.js';

const idlFactory$1 = ({IDL}) => {
  const DeckId = IDL.Text;
  const BucketId = IDL.Principal;
  return IDL.Service({
    del: IDL.Func([DeckId], [IDL.Bool], []),
    deleteDecksAdmin: IDL.Func([IDL.Principal], [], []),
    entries: IDL.Func([], [IDL.Vec(BucketId)], ['query']),
    get: IDL.Func([DeckId], [IDL.Opt(BucketId)], ['query']),
    init: IDL.Func([DeckId], [BucketId], [])
  });
};

const idlFactory = ({IDL}) => {
  const SlideId__1 = IDL.Text;
  const Time = IDL.Int;
  const DeckId = IDL.Text;
  const Deck = IDL.Record({
    updated_at: Time,
    data: IDL.Vec(IDL.Nat8),
    deckId: DeckId,
    created_at: Time
  });
  const SlideId = IDL.Text;
  const Slide = IDL.Record({
    updated_at: Time,
    data: IDL.Vec(IDL.Nat8),
    created_at: Time,
    slideId: SlideId
  });
  const DeckBucket = IDL.Service({
    delSlide: IDL.Func([SlideId__1], [IDL.Bool], []),
    get: IDL.Func([], [Deck], ['query']),
    getSlide: IDL.Func([SlideId__1], [Slide], ['query']),
    set: IDL.Func([Deck], [], []),
    setSlide: IDL.Func([Slide], [], []),
    transferCycles: IDL.Func([], [], [])
  });
  return DeckBucket;
};

const createManagerActor = ({ identity, host }) => {
  return createActor({ canisterId: process.env.MANAGER_CANISTER_ID, idlFactory: idlFactory$1, identity, host });
};
const createDeckBucketActor = ({ identity, bucket, host }) => {
  return createActor({ canisterId: bucket, idlFactory: idlFactory, identity, host });
};
const initDeckBucket = async ({ managerActor, deckId }) => {
  const existingBucket = fromNullable(await managerActor.get(deckId));
  if (!existingBucket) {
    return await managerActor.init(deckId);
  }
  return existingBucket;
};

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) })
  };
};
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');
};

const getSlide = (deckId, slideId) => {
  return new Promise(async (resolve, reject) => {
    const identity = getIdentity();
    if (!identity) {
      reject('No internet identity.');
      return;
    }
    try {
      const managerActor = await createManagerActor({ identity });
      const bucket = await initDeckBucket({ managerActor, deckId });
      const deckBucket = await createDeckBucketActor({ identity, bucket });
      const slide = await deckBucket.getSlide(slideId);
      const data = await fromArray(slide.data);
      resolve({
        id: slideId,
        data: Object.assign(Object.assign({}, data), { created_at: fromTimestamp(slide.created_at), updated_at: fromTimestamp(slide.updated_at) })
      });
    }
    catch (err) {
      reject(err);
    }
  });
};

// TODO: implement storage for the internet computer
const uploadFile = async (_param) => {
  return undefined;
};
const getFiles = async (_param) => {
  return null;
};
const getFolders = async (_param) => {
  return undefined;
};

const workerPromise = import('./sync.ic.worker-0480303d.js').then(m => m.worker);
const uploadWorker = /*@__PURE__*/createWorkerProxy(workerPromise, 'stencil.sync.ic.worker', 'uploadWorker');

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}`
  });
  await clean(syncData);
};

export { deckEntries, deleteDeck, getFiles, getFolders, getSlide, sync, uploadFile };
