import Vitals from "react-native-vitals";
import DeviceInfo from "react-native-device-info";
import { Platform } from "react-native";
const ifSufficentRAMAvailable = (ml_RAM) => {
  return new Promise((resolve, reject) => {
    try {
      Vitals.getMemory()
        .then((memory) => {
          var { appUsed, systemTotal, systemFree, systemUsed } = memory; // return in MB
          console.log(
            "*** CheckHardwareML ifSufficentRAMAvailable memory(MB): ",
            memory
          );
          if (systemFree) {
            // 1GB - iOS, 2GB - Android free RAM available
            const available = systemFree >= ml_RAM; // in MB
            resolve(available);
          } else {
            reject(false);
          }
        })
        .catch((error) => {
          reject(false);
        });
    } catch (error) {
      reject(false);
    }
  });
};

const isLatestAndroidVersion = (ml_OS_version) => {
  try {
    const osVersion = DeviceInfo.getSystemVersion();
    var myOSVersion = 0;
    if (osVersion && osVersion.indexOf(".") >= 0) {
      const majorMinorSubversion = osVersion.split(".");
      if (majorMinorSubversion && majorMinorSubversion.length > 0) {
        myOSVersion = majorMinorSubversion[0];
      }
    } else {
      myOSVersion = osVersion;
    }
    console.log(
      "*** CheckHardwareML isLatestAndroidVersion osVersion, myOSVersion: ",
      osVersion,
      myOSVersion
    );
    if (myOSVersion >= ml_OS_version) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    return false;
  }
};

// const ifSufficentRAMAvailable = () => {
//   return false;
// };

// const isLatestAndroidVersion = () => {
//   return false;
// };

const checkHardwareAvailableForML = async (ml_OS_version, ml_RAM) => {
  const sufficentRAMAvailable = await ifSufficentRAMAvailable(ml_RAM);
  const latestAndroidVersion =
    Platform.OS === "ios" ? true : isLatestAndroidVersion(ml_OS_version);
  console.log(
    "*** CheckHardwareML checkHardwareAvailableForML [sufficentRAMAvailable, latestAndroidVersion]: ",
    sufficentRAMAvailable,
    latestAndroidVersion
  );
  if (sufficentRAMAvailable && latestAndroidVersion) {
    return true;
  } else {
    return false;
  }
};

export { checkHardwareAvailableForML };
