import { toDate } from '@deckdeckgo/editor';
// See following link for a discussion about the format of the nullable values in the did files: https://forum.dfinity.org/t/fail-to-verify-certificate-in-development-update-calls/4078/14
export const toNullable = (value) => {
  return value ? [value] : [];
};
export const fromNullable = (value) => {
  return value === null || value === void 0 ? void 0 : value[0];
};
export const toTimestamp = (value) => {
  return BigInt(toDate(value).getTime());
};
export const toNullableTimestamp = (value) => {
  var _a;
  const time = (_a = toDate(value)) === null || _a === void 0 ? void 0 : _a.getTime();
  return value && !isNaN(time) ? [toTimestamp(value)] : [];
};
export const fromTimestamp = (value) => {
  return new Date(Number(value));
};
export const fromNullableTimestamp = (value) => {
  return !isNaN(parseInt(`${value === null || value === void 0 ? void 0 : value[0]}`)) ? new Date(`${value[0]}`) : undefined;
};
// Try to parse to number or boolean from string. It it fails, as for a string, use the value as it.
export const fromValue = (value) => {
  try {
    return JSON.parse(value);
  }
  catch (err) {
    return Array.isArray(value) ? value[0] : value;
  }
};
export const fromUserSocial = (userSocial) => {
  const result = Object.keys((userSocial === null || userSocial === void 0 ? void 0 : userSocial[0]) || {}).reduce((acc, key) => {
    const value = fromValue(userSocial[0][key]);
    if (value) {
      acc[key] = value;
    }
    return acc;
  }, {});
  return Object.keys(result).length ? result : undefined;
};
export const toUserSocial = (social) => {
  if (!social) {
    return [];
  }
  const { dev, linkedin, twitter, custom_logo_url, custom, github, medium } = social;
  return [
    {
      dev: toNullable(dev),
      linkedin: toNullable(linkedin),
      twitter: toNullable(twitter),
      custom_logo_url: toNullable(custom_logo_url),
      custom: toNullable(custom),
      github: toNullable(github),
      medium: toNullable(medium)
    }
  ];
};
export const toArray = async (data) => {
  const blob = new Blob([JSON.stringify(data)], { type: 'application/json; charset=utf-8' });
  return [...new Uint8Array(await blob.arrayBuffer())];
};
export const fromArray = async (data) => {
  const blob = new Blob([new Uint8Array(data)], { type: 'application/json; charset=utf-8' });
  return JSON.parse(await blob.text());
};
