"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
const logs_1 = require("@ledgerhq/logs");
const api_1 = __importDefault(require("../manager/api"));
const provider_1 = require("../manager/provider");
const getDeviceInfo_1 = __importDefault(require("./getDeviceInfo"));
const fetchMcusUseCase_1 = require("../device/use-cases/fetchMcusUseCase");
const blVersionAliases = {
    "0.0": "0.6",
};
function default_1({ mcu_versions }) {
    return (transport) => (0, rxjs_1.from)((0, getDeviceInfo_1.default)(transport)).pipe((0, operators_1.mergeMap)((deviceInfo) => (deviceInfo.majMin in blVersionAliases
        ? (0, rxjs_1.of)(blVersionAliases[deviceInfo.majMin])
        : (0, rxjs_1.from)((0, fetchMcusUseCase_1.fetchMcusUseCase)().then((mcus) => {
            const provider = (0, provider_1.getProviderId)(deviceInfo);
            const filtered = mcus.filter(({ from_bootloader_version, id, providers }) => providers.includes(provider) &&
                from_bootloader_version !== "none" &&
                mcu_versions.includes(id));
            return api_1.default.findBestMCU(filtered);
        }))).pipe((0, operators_1.mergeMap)((mcuVersion) => {
        if (!mcuVersion)
            return rxjs_1.EMPTY;
        let version;
        let isMCU = false;
        if (typeof mcuVersion === "string") {
            version = mcuVersion;
            (0, logs_1.log)("firmware-update", `flash ${version} from mcuVersion`);
        }
        else {
            const mcuFromBootloader = (mcuVersion.from_bootloader_version ?? "")
                .split(".")
                .slice(0, 3)
                .join(".");
            isMCU = deviceInfo.majMin === mcuFromBootloader;
            version = isMCU ? mcuVersion.name : mcuFromBootloader;
            (0, logs_1.log)("firmware-update", `flash ${version} isMcu=${isMCU}`, {
                blVersion: deviceInfo.majMin,
                mcuFromBootloader,
                version,
                isMCU,
            });
        }
        return (0, rxjs_1.concat)((0, rxjs_1.of)({
            type: "install",
            step: `flash-${isMCU ? "mcu" : "bootloader"}`,
        }), api_1.default.installMcu(transport, "mcu", {
            targetId: deviceInfo.targetId,
            version,
        }));
    }))));
}
exports.default = default_1;
//# sourceMappingURL=flash.js.map