"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setDataDir = exports.useIndexOverride = exports.updateToLatest = exports.isUpdateAvailable = exports.getImageMeta = void 0;
const url = 'https://raw.githubusercontent.com/Koenkk/zigbee-OTA/master/index.json';
const common = __importStar(require("./common"));
const axios = common.getAxios();
const fs_1 = __importDefault(require("fs"));
const URI = __importStar(require("uri-js"));
const path_1 = __importDefault(require("path"));
let overrideIndexFileName = null;
let dataDir = null;
/**
 * Helper functions
 */
function isValidUrl(url) {
    let parsed;
    try {
        parsed = URI.parse(url);
    }
    catch (_) {
        return false;
    }
    return parsed.scheme === 'http' || parsed.scheme === 'https';
}
async function getIndexFile(urlOrName) {
    if (isValidUrl(urlOrName)) {
        return (await axios.get(urlOrName)).data;
    }
    return JSON.parse(fs_1.default.readFileSync(urlOrName, 'utf-8'));
}
function readLocalFile(fileName, logger) {
    // If the file name is not a full path, then treat it as a relative to the data directory
    if (!path_1.default.isAbsolute(fileName) && dataDir) {
        fileName = path_1.default.join(dataDir, fileName);
    }
    logger.debug(`ZigbeeOTA: getting local firmware file ${fileName}`);
    return fs_1.default.readFileSync(fileName);
}
async function getFirmwareFile(image, logger) {
    const urlOrName = image.url;
    // First try to download firmware file with the URL provided
    if (isValidUrl(urlOrName)) {
        logger.debug(`ZigbeeOTA: downloading firmware image from ${urlOrName}`);
        return await axios.get(urlOrName, { responseType: 'arraybuffer' });
    }
    return { data: readLocalFile(urlOrName, logger) };
}
function fillImageInfo(meta, logger) {
    // Web-hosted images must come with all fields filled already
    if (isValidUrl(meta.url)) {
        return meta;
    }
    // Nothing to do if needed fields were filled already
    if (meta.hasOwnProperty('imageType') &&
        meta.hasOwnProperty('manufacturerCode') &&
        meta.hasOwnProperty('fileVersion')) {
        return meta;
    }
    // If no fields provided - get them from the image file
    const buffer = readLocalFile(meta.url, logger);
    const start = buffer.indexOf(common.upgradeFileIdentifier);
    const image = common.parseImage(buffer.slice(start));
    // Will fill only those fields that were absent
    if (!meta.hasOwnProperty('imageType'))
        meta.imageType = image.header.imageType;
    if (!meta.hasOwnProperty('manufacturerCode'))
        meta.manufacturerCode = image.header.manufacturerCode;
    if (!meta.hasOwnProperty('fileVersion'))
        meta.fileVersion = image.header.fileVersion;
    return meta;
}
async function getIndex(logger) {
    const index = (await axios.get(url)).data;
    logger.debug(`ZigbeeOTA: downloaded main index`);
    if (overrideIndexFileName) {
        logger.debug(`ZigbeeOTA: Loading override index ${overrideIndexFileName}`);
        const localIndex = await getIndexFile(overrideIndexFileName);
        // Resulting index will have overriden items first
        return localIndex.concat(index).map((item) => isValidUrl(item.url) ? item : fillImageInfo(item, logger));
    }
    return index;
}
async function getImageMeta(current, logger, device) {
    const modelId = device.modelID;
    const imageType = current.imageType;
    const manufacturerCode = current.manufacturerCode;
    const manufacturerName = device.manufacturerName;
    const images = await getIndex(logger);
    // NOTE: Officially an image can be determined with a combination of manufacturerCode and imageType.
    // However Gledopto pro products use the same imageType (0) for every device while the image is different.
    // For this case additional identification through the modelId is done.
    // In the case of Tuya and Moes, additional identification is carried out through the manufacturerName.
    const image = images.find((i) => i.imageType === imageType && i.manufacturerCode === manufacturerCode &&
        (!i.minFileVersion || current.fileVersion >= i.minFileVersion) && (!i.maxFileVersion || current.fileVersion <= i.maxFileVersion) &&
        (!i.modelId || i.modelId === modelId) && (!i.manufacturerName || i.manufacturerName.includes(manufacturerName)));
    if (!image) {
        throw new Error(`No image available for imageType '${imageType}'`);
    }
    return {
        fileVersion: image.fileVersion,
        fileSize: image.fileSize,
        url: image.url,
        sha512: image.sha512,
        force: image.force,
    };
}
exports.getImageMeta = getImageMeta;
async function isNewImageAvailable(current, logger, device, getImageMeta) {
    if (device.modelID === 'lumi.airrtc.agl001') {
        // The current.fileVersion which comes from the device is wrong.
        // Use the `aqaraFileVersion` which comes from the aqaraOpple.attributeReport instead.
        // https://github.com/Koenkk/zigbee2mqtt/issues/16345#issuecomment-1454835056
        // https://github.com/Koenkk/zigbee2mqtt/issues/16345 doesn't seem to be needed for all
        if (device.meta.aqaraFileVersion) {
            current = { ...current, fileVersion: device.meta.aqaraFileVersion };
        }
    }
    return common.isNewImageAvailable(current, logger, device, getImageMeta);
}
/**
 * Interface implementation
 */
async function isUpdateAvailable(device, logger, requestPayload = null) {
    return common.isUpdateAvailable(device, logger, isNewImageAvailable, requestPayload, getImageMeta);
}
exports.isUpdateAvailable = isUpdateAvailable;
async function updateToLatest(device, logger, onProgress) {
    return common.updateToLatest(device, logger, onProgress, common.getNewImage, getImageMeta, getFirmwareFile);
}
exports.updateToLatest = updateToLatest;
const useIndexOverride = (indexFileName) => {
    overrideIndexFileName = indexFileName;
};
exports.useIndexOverride = useIndexOverride;
const setDataDir = (dir) => {
    dataDir = dir;
};
exports.setDataDir = setDataDir;
exports.getImageMeta = getImageMeta;
exports.isUpdateAvailable = isUpdateAvailable;
exports.updateToLatest = updateToLatest;
exports.useIndexOverride = exports.useIndexOverride;
exports.setDataDir = exports.setDataDir;
//# sourceMappingURL=zigbeeOTA.js.map