"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useDeviceHasUpdatesAvailable = void 0;
const react_1 = require("react");
const semver_1 = __importDefault(require("semver"));
const env_react_1 = require("../env.react");
const getLatestFirmwareForDeviceUseCase_1 = require("../device/use-cases/getLatestFirmwareForDeviceUseCase");
const getAppsCatalogForDevice_1 = require("../device/use-cases/getAppsCatalogForDevice");
async function hasOutdatedApps({ deviceInfo, apps }) {
    const appsCatalog = await (0, getAppsCatalogForDevice_1.getAppsCatalogForDevice)(deviceInfo);
    return apps.some(app => {
        const currApp = appsCatalog.find(e => e.versionName === app.name);
        return currApp && semver_1.default.gt(currApp.version, app.version);
    });
}
/**
 * Check if the device has updates available (firmware or apps)
 * @param dmi DeviceModelInfo
 * @returns boolean (true if some updates are available)
 */
function useDeviceHasUpdatesAvailable(dmi) {
    const [display, setDisplay] = (0, react_1.useState)(!dmi);
    const forceProvider = (0, env_react_1.useEnv)("FORCE_PROVIDER");
    (0, react_1.useEffect)(() => {
        let cancelled = false;
        function cancel() {
            cancelled = true;
        }
        if (!dmi) {
            setDisplay(true);
            return cancel;
        }
        const { deviceInfo } = dmi;
        Promise.all([(0, getLatestFirmwareForDeviceUseCase_1.getLatestFirmwareForDeviceUseCase)(deviceInfo), hasOutdatedApps(dmi)])
            .then(([fw, outdatedApp]) => {
            if (cancelled)
                return;
            if (fw || outdatedApp) {
                setDisplay(true);
                return;
            }
            setDisplay(Boolean(fw || outdatedApp));
        })
            .catch(err => {
            if (cancelled)
                return;
            console.error(err);
            setDisplay(false);
        });
        return cancel;
    }, [dmi, forceProvider]);
    return display;
}
exports.useDeviceHasUpdatesAvailable = useDeviceHasUpdatesAvailable;
//# sourceMappingURL=useDeviceHasUpdatesAvailable.js.map