"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "PluginFirmwareUpdateService", {
    enumerable: true,
    get: function() {
        return PluginFirmwareUpdateService;
    }
});
const _pluginbaseservice = require("./plugin-base.service");
const _runtimeexceptions = require("../../exceptions/runtime.exceptions");
const _firmwareupdatesettingsconstants = require("./constants/firmware-update-settings.constants");
const config = {
    pluginName: "firmwareupdater",
    pluginUrl: "https://github.com/OctoPrint/OctoPrint-FirmwareUpdater/archive/master.zip"
};
const defaultRepos = {
    prusaFirmwareOwner: "prusa3d",
    prusaFirmwareRepo: "Prusa-Firmware"
};
const connectivityProp = "connectivity.connection_ok";
const firmwareProp = "printer.firmware";
const firmwareDownloadPath = "firmware-downloads";
class PluginFirmwareUpdateService extends _pluginbaseservice.PluginBaseService {
    githubService;
    multerService;
    prusaFirmwareReleases;
    latestFirmware;
    constructor({ octoprintClient, pluginRepositoryCache, githubService, multerService, loggerFactory }){
        super({
            octoprintClient,
            pluginRepositoryCache,
            loggerFactory
        }, config);
        this.octoprintClient = octoprintClient;
        this.githubService = githubService;
        this.multerService = multerService;
    }
    async queryGithubPrusaFirmwareReleasesCache() {
        try {
            const response = await this.githubService.getReleases(defaultRepos.prusaFirmwareOwner, defaultRepos.prusaFirmwareRepo);
            this.prusaFirmwareReleases = response.data;
        } catch (e) {
            return this.logger.error("Github fetch error. Probably rate limited, skipping firmware download");
        }
        if (!this.prusaFirmwareReleases?.length) return [];
        this.latestFirmware = this.prusaFirmwareReleases[0];
        this.logger.log(`Plugin Cache filled with ${this.prusaFirmwareReleases?.length || "?"} firmware releases`, {
            url: this.latestFirmware.url,
            tag_name: this.latestFirmware.tag_name
        });
        return this.prusaFirmwareReleases;
    }
    async downloadFirmware() {
        if (!this.prusaFirmwareReleases?.length || !this.latestFirmware) {
            throw new _runtimeexceptions.ValidationException("No firmware releases were scanned. Download was not successful");
        }
        const latestFirmware = this.prusaFirmwareReleases[0];
        const firmwareAsset = latestFirmware.assets.find((asset)=>asset.name.includes("MK3S_MK3S+"));
        const downloadUrl = firmwareAsset.browser_download_url;
        const downloadName = firmwareAsset.name;
        this.logger.log(`Checking firmware ${downloadName}`);
        if (!this.multerService.fileExists(downloadName, firmwareDownloadPath)) {
            this.logger.log(`Downloading firmware from ${downloadUrl}`);
            await this.multerService.downloadFile(downloadUrl, downloadName, firmwareDownloadPath);
            this.logger.log(`Downloaded firmware ${downloadName}`);
        } else {
            this.logger.log(`Found firmware ${downloadName}`);
        }
    }
    async getPrinterFirmwareVersion(printerLogin) {
        const response = await this.octoprintClient.getSystemInfo(printerLogin);
        const systemInfo = response.systeminfo;
        if (!Object.keys(systemInfo).includes(connectivityProp) || !Object.keys(systemInfo).includes(firmwareProp)) {
            throw new _runtimeexceptions.ValidationException("Could not retrieve printer firmware version as the OctoPrint response was not recognized. Is it connected?");
        }
        const connected = systemInfo[connectivityProp];
        if (!connected) {
            throw new _runtimeexceptions.ValidationException("OctoPrint printer is not connected and firmware cannot be checked");
        }
        const firmware = systemInfo[firmwareProp];
        if (!firmware?.length) {
            throw new _runtimeexceptions.ValidationException("OctoPrint firmware version property was not recognized");
        }
        return firmware;
    }
    async getPluginFirmwareStatus(printerLogin) {
        return await this.octoprintClient.getPluginFirmwareUpdateStatus(printerLogin);
    }
    async configureFirmwareUpdaterSettings(printerLogin) {
        return await this.octoprintClient.updateFirmwareUpdaterSettings(printerLogin, _firmwareupdatesettingsconstants.defaultFirmwareUpdaterSettings);
    }
    async flashPrusaFirmware(currentPrinterId, printerLogin) {
        const latestHexFilePath = this.multerService.getNewestFile(firmwareDownloadPath);
        return await this.octoprintClient.postPluginFirmwareUpdateFlash(currentPrinterId, printerLogin, latestHexFilePath);
    }
}

//# sourceMappingURL=plugin-firmware-update.service.js.map