"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("../common/constants");
const decorators_1 = require("../common/decorators");
const events_1 = require("events");
class LogParserService extends events_1.EventEmitter {
    constructor($deviceLogProvider, $devicesService, $errors) {
        super();
        this.$deviceLogProvider = $deviceLogProvider;
        this.$devicesService = $devicesService;
        this.$errors = $errors;
        this.parseRules = {};
    }
    addParseRule(rule) {
        if (this.parseRules[rule.name]) {
            this.$errors.failWithoutHelp("Log parse rule already exists.");
        }
        this.parseRules[rule.name] = rule;
        this.startParsingLogCore();
    }
    startParsingLogCore() {
        this.$deviceLogProvider.on(constants_1.DEVICE_LOG_EVENT_NAME, (message, deviceIdentifier) => this.processDeviceLogResponse(message, deviceIdentifier));
    }
    processDeviceLogResponse(message, deviceIdentifier) {
        const device = this.$devicesService.getDeviceByIdentifier(deviceIdentifier);
        const devicePlatform = device.deviceInfo.platform.toLowerCase();
        _.forEach(this.parseRules, (parseRule) => {
            if (!parseRule.platform || parseRule.platform.toLowerCase() === devicePlatform) {
                const matches = parseRule.regex.exec(message);
                if (matches) {
                    parseRule.handler(matches, deviceIdentifier);
                }
            }
        });
    }
}
__decorate([
    decorators_1.cache()
], LogParserService.prototype, "startParsingLogCore", null);
exports.LogParserService = LogParserService;
$injector.register("logParserService", LogParserService);
