import { nanoid } from 'nanoid';
import { initIdentity } from '../utils/identity.utils';
import { getDataBucket } from '../utils/manager.utils';
import { getData, setData } from '../utils/data.utils';
export const initUserWorker = ({ internetIdentity, host }, onInitUserSuccess) => initUser({ internetIdentity, host }, onInitUserSuccess);
const initUser = async ({ internetIdentity: { delegationChain, identityKey }, host }, onInitUserSuccess) => new Promise(async (resolve) => {
  if (!delegationChain || !identityKey) {
    resolve();
    return;
  }
  const identity = initIdentity({ identityKey, delegationChain });
  const { actor } = await getDataBucket({ identity, host });
  if (!actor) {
    setTimeout(async () => {
      await initUser({ internetIdentity: { delegationChain, identityKey }, host }, onInitUserSuccess);
      resolve();
    }, 2000);
    return;
  }
  const user = await initUserData({ actor });
  await onInitUserSuccess(user);
  resolve();
});
const initUserData = async ({ actor }) => {
  console.log('User IC about to GET');
  const t0 = performance.now();
  const user = await getData({ key: `/user`, actor });
  const t1 = performance.now();
  console.log('User IC GET done', t1 - t0, user);
  if (!user) {
    const newUser = await createUser({ actor });
    return newUser;
  }
  return user;
};
const createUser = async ({ actor }) => {
  const now = new Date();
  const id = nanoid();
  const data = {
    created_at: now,
    updated_at: now
  };
  console.log('User IC about to SET');
  const t0 = performance.now();
  const user = await setData({ key: `/user`, id, data, actor });
  const t1 = performance.now();
  console.log('User IC SET done', t1 - t0);
  return user;
};
