"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 fs = require("fs-extra");
const common_1 = require("@nestjs/common");
const hap_client_1 = require("@oznu/hap-client");
const config_service_1 = require("../../core/config/config.service");
const logger_service_1 = require("../../core/logger/logger.service");
let AccessoriesService = class AccessoriesService {
    constructor(configService, logger) {
        this.configService = configService;
        this.logger = logger;
        if (this.configService.homebridgeInsecureMode) {
            this.hapClient = new hap_client_1.HapClient({
                pin: this.configService.homebridgeConfig.bridge.pin,
                logger: this.logger,
                config: this.configService.ui.accessoryControl || {},
            });
        }
    }
    connect(client) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.configService.homebridgeInsecureMode) {
                this.logger.error('Homebridge must be running in insecure mode to control accessories');
                return;
            }
            let services;
            services = yield this.loadAccessories();
            this.refreshCharacteristics(services);
            client.emit('accessories-data', services);
            const requestHandler = (msg) => __awaiter(this, void 0, void 0, function* () {
                if (msg.set) {
                    const service = services.find(x => x.uniqueId === msg.set.uniqueId);
                    if (service) {
                        yield service.setCharacteristic(msg.set.iid, msg.set.value);
                        services = yield this.loadAccessories();
                        setTimeout(() => {
                            this.refreshCharacteristics(services);
                        }, 1500);
                    }
                }
            });
            client.on('accessory-control', requestHandler);
            const monitor = yield this.hapClient.monitorCharacteristics();
            const updateHandler = (data) => {
                client.emit('accessories-data', data);
            };
            monitor.on('service-update', updateHandler);
            const instanceUpdateHandler = (data) => __awaiter(this, void 0, void 0, function* () {
                client.emit('accessories-reload-required', services);
            });
            this.hapClient.on('instance-discovered', instanceUpdateHandler);
            const onEnd = () => {
                client.removeAllListeners('end');
                client.removeAllListeners('disconnect');
                client.removeAllListeners('accessory-control');
                monitor.removeAllListeners('service-update');
                monitor.finish();
                this.hapClient.removeListener('instance-discovered', instanceUpdateHandler);
            };
            client.on('disconnect', onEnd.bind(this));
            client.on('end', onEnd.bind(this));
            this.hapClient.refreshInstances();
        });
    }
    refreshCharacteristics(services) {
        services.forEach(service => service.refreshCharacteristics());
    }
    loadAccessories(refreshServices) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.hapClient.getAllServices()
                .then(services => {
                return services;
            })
                .catch((e) => {
                if (e.statusCode === 401) {
                    this.logger.warn(`Homebridge must be running in insecure mode to view and control accessories from this plugin.`);
                }
                else {
                    this.logger.error(`Failed load accessories from Homebridge: ${e.message}`);
                }
                return [];
            });
        });
    }
    getAccessoryLayout(username) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const accessoryLayout = yield fs.readJson(this.configService.accessoryLayoutPath);
                if (username in accessoryLayout) {
                    return accessoryLayout[username];
                }
                else {
                    throw new Error('User not in Acccessory Layout');
                }
            }
            catch (e) {
                return [
                    {
                        name: 'Default Room',
                        services: [],
                    },
                ];
            }
        });
    }
    saveAccessoryLayout(user, layout) {
        return __awaiter(this, void 0, void 0, function* () {
            let accessoryLayout;
            try {
                accessoryLayout = yield fs.readJson(this.configService.accessoryLayoutPath);
            }
            catch (e) {
                accessoryLayout = {};
            }
            accessoryLayout[user] = layout;
            fs.writeJsonSync(this.configService.accessoryLayoutPath, accessoryLayout);
            this.logger.log(`[${user}] Accessory layout changes saved.`);
            return layout;
        });
    }
};
AccessoriesService = __decorate([
    common_1.Injectable(),
    __metadata("design:paramtypes", [config_service_1.ConfigService,
        logger_service_1.Logger])
], AccessoriesService);
exports.AccessoriesService = AccessoriesService;
//# sourceMappingURL=accessories.service.js.map