Source: lib/helper/general/index.js

import { MD5 } from "object-hash";

export const arrayIsTheSame = (prev, curr) => prev.length === curr.length && curr.every((element, index) => element === prev[index]);

/**
 * @see https://stackoverflow.com/a/53930826
 * @param {string} str
 * @param {string} [locale]
 * @returns {string} Capitalized string
 */
export const capitalizeFirstLetter = (str, locale = window?.navigator?.language) => str.replace(/^\p{CWU}/u, (char) => char.toLocaleUpperCase(locale));

/**
 * Sort two uuidv1 uuid's.
 * @see https://github.com/uuidjs/uuid/issues/75#issuecomment-302916409
 * @param {string} a
 * @param {string} b
 * @returns {number} Array sort number
 */
export const v1UuidSort = (a, b) => {
  a = a.replace(/^(.{8})-(.{4})-(.{4})/, "$3-$2-$1");
  b = b.replace(/^(.{8})-(.{4})-(.{4})/, "$3-$2-$1");
  return a < b ? -1 : a > b ? 1 : 0;
};

export const generateFormDisplayName = (version = 1, formName) => {
  if (version === 1) {
    return `1673737200/${formName}`;
  }
  if (version === 2) {
    return `1675724400/${formName}`;
  }
  if (version === 3) {
    return `1693432800/${formName}`;  // nissewaard
  }
  throw Error("Incorrect form version used when generating a form name");
};

// Note: isBrowser will fail within WebWorkers, SharedWorker and ServiceWorker
// https://github.com/pmndrs/zustand/blob/833f57ed131e94f3ed48627d4cfbf09cb9c7df03/src/react.ts#L20-L23
export const isBrowser = !(typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent));

export const isPositiveInteger = (value) => Math.sign(value) === 1 && Number.isInteger(value);

export const convertToInput = (value) => ({ input: { signature: MD5(value), value } });

export const createDownloadLink = (link, fileName) => {
  if (link) {
    const element = document.createElement("a");
    element.href = link;
    element.referrerPolicy = "no-referrer";
    element.class = "hidden";
    element.target = "_blank"; // Because our URL is not the same origin we must open in another tab :(
    // element.type = ""; // Could be used later on when we have verified the mimetype
    if (fileName) {
      element.download = fileName;
    }
    // simulate link click
    window?.document.body.appendChild(element); // Required for this to work in FireFox
    element.click();
    window?.document.body.removeChild(element);
  }
}