import Dexie from "dexie";

export const APPVERSION = "0.4.4";

export const set_version = () => {
  localStorage.setItem("version", APPVERSION);
};

export const get_version = () => {
  return localStorage.getItem("version") as string | null;
};

export const getVersionGroup = (version: string) => {
  return version.split(".").map((i) => Number(i));
};

export const checkVersionAndDoSomething = async () => {
  const oldVersion = get_version();
  const currentVersion = APPVERSION;
  set_version();
  console.log("version:", currentVersion);

  if (!oldVersion || compareVersion(oldVersion, "0.4.2") === -1) {
    return Dexie.delete("MyAppDatabase")
      .then((r) => {
        console.log(r, "success");
      })
      .catch((f) => {
        console.log(f, "faill");
      });
  }
};

/**
 *
 * @param version1 版本1
 * @param version2 版本2
 * @returns 版本1大于版本2 返回 1，小于返回-1，等于返回0
 */
export const compareVersion = (version1: string, version2: string) => {
  const vg1 = getVersionGroup(version1);
  const vg2 = getVersionGroup(version2);

  for (let i = 0; i < 3; ++i) {
    if (vg1[i] < vg2[i]) {
      return -1;
    } else if (vg1[i] > vg2[i]) {
      return 1;
    }
  }
  return 0;
};
