"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __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 });
const node_assert_1 = __importDefault(require("node:assert"));
const device_1 = require("zigbee-herdsman/dist/controller/model/device");
const zhc = __importStar(require("zigbee-herdsman-converters"));
const zigbee_herdsman_converters_1 = require("zigbee-herdsman-converters");
const logger_1 = __importDefault(require("../util/logger"));
const settings = __importStar(require("../util/settings"));
const LINKQUALITY = new zigbee_herdsman_converters_1.Numeric("linkquality", zigbee_herdsman_converters_1.access.STATE)
    .withUnit("lqi")
    .withDescription("Link quality (signal strength)")
    .withValueMin(0)
    .withValueMax(255)
    .withCategory("diagnostic");
class Device {
    zh;
    definition;
    _definitionModelID;
    #isResolvingDefinition;
    get ieeeAddr() {
        return this.zh.ieeeAddr;
    }
    // biome-ignore lint/style/useNamingConvention: API
    get ID() {
        return this.zh.ieeeAddr;
    }
    get options() {
        const deviceOptions = settings.getDevice(this.ieeeAddr) ?? { friendly_name: this.ieeeAddr, ID: this.ieeeAddr };
        return { ...settings.get().device_options, ...deviceOptions };
    }
    get name() {
        return this.zh.type === "Coordinator" ? "Coordinator" : this.options?.friendly_name;
    }
    get isSupported() {
        return this.zh.type === "Coordinator" || Boolean(this.definition && !this.definition.generated);
    }
    get customClusters() {
        return this.zh.customClusters;
    }
    get otaExtraMetas() {
        return typeof this.definition?.ota === "object" ? this.definition.ota : {};
    }
    get interviewed() {
        return this.zh.interviewState === device_1.InterviewState.Successful || this.zh.interviewState === device_1.InterviewState.Failed;
    }
    constructor(device) {
        this.zh = device;
    }
    exposes() {
        const exposes = [];
        (0, node_assert_1.default)(this.definition, "Cannot retreive exposes before definition is resolved");
        if (typeof this.definition.exposes === "function") {
            const options = this.options;
            exposes.push(...this.definition.exposes(this.zh, options));
        }
        else {
            exposes.push(...this.definition.exposes);
        }
        exposes.push(LINKQUALITY);
        return exposes;
    }
    async resolveDefinition(ignoreCache = false) {
        if (this.interviewed && !this.#isResolvingDefinition && (!this.definition || this._definitionModelID !== this.zh.modelID || ignoreCache)) {
            this.#isResolvingDefinition = true;
            this.definition = await zhc.findByDevice(this.zh, true);
            this._definitionModelID = this.zh.modelID;
            this.#isResolvingDefinition = false;
        }
    }
    async reInterview(eventBus) {
        // logic follows that of receiving `deviceInterview` event from ZH layer
        logger_1.default.info(`Interviewing '${this.name}'`);
        eventBus.emitDeviceInterview({ status: "started", device: this });
        try {
            await this.zh.interview(true);
            // A re-interview can for example result in a different modelId, therefore reconsider the definition.
            await this.resolveDefinition(true);
            logger_1.default.info(`Successfully interviewed '${this.name}'`);
            eventBus.emitDeviceInterview({ status: "successful", device: this });
        }
        catch (error) {
            eventBus.emitDeviceInterview({ status: "failed", device: this });
            throw new Error(`Interview of '${this.name}' (${this.ieeeAddr}) failed: ${error}`);
        }
    }
    ensureInSettings() {
        if (this.zh.type !== "Coordinator" && !settings.getDevice(this.zh.ieeeAddr)) {
            settings.addDevice(this.zh.ieeeAddr);
        }
    }
    endpoint(key) {
        if (!key) {
            key = "default";
        }
        else if (!Number.isNaN(Number(key))) {
            return this.zh.getEndpoint(Number(key));
        }
        if (this.definition?.endpoint) {
            const ID = this.definition.endpoint(this.zh)[key];
            if (ID) {
                return this.zh.getEndpoint(ID);
            }
        }
        return key === "default" ? this.zh.endpoints[0] : undefined;
    }
    endpointName(endpoint) {
        let epName;
        if (this.definition?.endpoint) {
            const mapping = this.definition.endpoint(this.zh);
            for (const name in mapping) {
                if (mapping[name] === endpoint.ID) {
                    epName = name;
                    break;
                }
            }
        }
        /* v8 ignore next */
        return epName === "default" ? undefined : epName;
    }
    getEndpointNames() {
        const names = [];
        if (this.definition?.endpoint) {
            for (const name in this.definition.endpoint(this.zh)) {
                if (name !== "default") {
                    names.push(name);
                }
            }
        }
        return names;
    }
    isDevice() {
        return true;
    }
    isGroup() {
        return false;
    }
}
exports.default = Device;
//# sourceMappingURL=data:application/json;base64, 