"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = require("os");
const fs = require("fs-extra");
const rp = require("request-promise-native");
const common_1 = require("@nestjs/common");
const config_service_1 = require("../../core/config/config.service");
const logger_service_1 = require("../../core/logger/logger.service");
let StatusService = class StatusService {
    constructor(logger, configService) {
        this.logger = logger;
        this.configService = configService;
    }
    watchStats(client) {
        return __awaiter(this, void 0, void 0, function* () {
            client.emit('system-status', yield this.getSystemStats());
            client.emit('homebridge-status', yield this.getHomebridgeStats());
            const systemStatusInterval = setInterval(() => __awaiter(this, void 0, void 0, function* () {
                client.emit('system-status', yield this.getSystemStats());
            }), 5000);
            const homebridgeStatusInterval = setInterval(() => __awaiter(this, void 0, void 0, function* () {
                client.emit('homebridge-status', yield this.getHomebridgeStats());
            }), 10000);
            const onEnd = () => {
                client.removeAllListeners('end');
                client.removeAllListeners('disconnect');
                clearInterval(systemStatusInterval);
                clearInterval(homebridgeStatusInterval);
            };
            client.on('end', onEnd.bind(this));
            client.on('disconnect', onEnd.bind(this));
        });
    }
    getHomebridgeStats() {
        return __awaiter(this, void 0, void 0, function* () {
            return {
                consolePort: this.configService.ui.port,
                port: this.configService.homebridgeConfig.bridge.port,
                pin: this.configService.homebridgeConfig.bridge.pin,
                packageVersion: this.configService.package.version,
                status: yield this.checkHomebridgeStatus(),
            };
        });
    }
    getSystemStats() {
        return __awaiter(this, void 0, void 0, function* () {
            const memory = {
                total: (((os.totalmem() / 1024) / 1024) / 1024).toFixed(2),
                used: ((((os.totalmem() - os.freemem()) / 1024) / 1024) / 1024).toFixed(2),
                free: (((os.freemem() / 1024) / 1024) / 1024).toFixed(2),
            };
            const cpu = (os.platform() === 'win32') ? null : (os.loadavg()[0] * 100 / os.cpus().length).toFixed(2);
            const uptime = {
                delta: Math.floor(os.uptime()),
            };
            uptime.days = Math.floor(uptime.delta / 86400);
            uptime.delta -= uptime.days * 86400;
            uptime.hours = Math.floor(uptime.delta / 3600) % 24;
            uptime.delta -= uptime.hours * 3600;
            uptime.minutes = Math.floor(uptime.delta / 60) % 60;
            let cputemp = null;
            if (this.configService.ui.temp) {
                try {
                    cputemp = yield fs.readFile(this.configService.ui.temp, 'utf-8');
                    cputemp = ((cputemp / 1000).toPrecision(3));
                }
                catch (e) {
                    cputemp = null;
                    this.logger.error(`Failed to read temp from ${this.configService.ui.temp}`);
                }
            }
            return {
                memory,
                cpu,
                uptime,
                cputemp,
            };
        });
    }
    checkHomebridgeStatus() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                yield rp.get(`http://localhost:${this.configService.homebridgeConfig.bridge.port}`, {
                    resolveWithFullResponse: true,
                    simple: false,
                });
                return 'up';
            }
            catch (e) {
                return 'down';
            }
        });
    }
};
StatusService = __decorate([
    common_1.Injectable(),
    __metadata("design:paramtypes", [logger_service_1.Logger,
        config_service_1.ConfigService])
], StatusService);
exports.StatusService = StatusService;
//# sourceMappingURL=status.service.js.map