"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PreviewDevicesService = void 0;
const events_1 = require("events");
const constants_1 = require("../../../../common/constants");
const _ = require("lodash");
const yok_1 = require("../../../../common/yok");
class PreviewDevicesService extends events_1.EventEmitter {
    constructor($previewAppLogProvider, $previewAppPluginsService) {
        super();
        this.$previewAppLogProvider = $previewAppLogProvider;
        this.$previewAppPluginsService = $previewAppPluginsService;
        this.connectedDevices = [];
        this.deviceLostTimers = {};
        this.initialize();
    }
    getConnectedDevices() {
        return this.connectedDevices;
    }
    updateConnectedDevices(devices) {
        _(devices)
            .reject((d) => _.some(this.connectedDevices, (device) => d.id === device.id))
            .each((device) => this.raiseDeviceFound(device));
        _(this.connectedDevices)
            .reject((d) => _.some(devices, (device) => d.id === device.id))
            .each((device) => this.raiseDeviceLostAfterTimeout(device));
    }
    getDeviceById(id) {
        return _.find(this.connectedDevices, { id });
    }
    getDevicesForPlatform(platform) {
        return _.filter(this.connectedDevices, {
            platform: platform.toLowerCase(),
        });
    }
    getPluginsUsageWarnings(data, device) {
        return this.$previewAppPluginsService.getPluginsUsageWarnings(data, device);
    }
    initialize() {
        this.$previewAppLogProvider.on(constants_1.DEVICE_LOG_EVENT_NAME, (deviceId, message) => {
            this.emit(constants_1.DEVICE_LOG_EVENT_NAME, deviceId, message);
        });
    }
    raiseDeviceFound(device) {
        if (this.deviceLostTimers[device.id]) {
            clearTimeout(this.deviceLostTimers[device.id]);
            this.deviceLostTimers[device.id] = null;
        }
        this.emit(constants_1.DeviceDiscoveryEventNames.DEVICE_FOUND, device);
        this.connectedDevices.push(device);
    }
    raiseDeviceLost(device) {
        this.emit(constants_1.DeviceDiscoveryEventNames.DEVICE_LOST, device);
        _.remove(this.connectedDevices, (d) => d.id === device.id);
    }
    raiseDeviceLostAfterTimeout(device) {
        if (!this.deviceLostTimers[device.id]) {
            const timeoutId = setTimeout(() => {
                this.raiseDeviceLost(device);
                clearTimeout(timeoutId);
            }, 5 * 1000);
            this.deviceLostTimers[device.id] = timeoutId;
        }
    }
}
exports.PreviewDevicesService = PreviewDevicesService;
yok_1.injector.register("previewDevicesService", PreviewDevicesService);
