"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 });
exports.LogParserService = void 0;
const constants_1 = require("../common/constants");
const decorators_1 = require("../common/decorators");
const events_1 = require("events");
const _ = require("lodash");
const yok_1 = require("../common/yok");
class LogParserService extends events_1.EventEmitter {
    constructor($deviceLogProvider, $errors) {
        super();
        this.$deviceLogProvider = $deviceLogProvider;
        this.$errors = $errors;
        this.parseRules = {};
    }
    addParseRule(rule) {
        if (this.parseRules[rule.name]) {
            this.$errors.fail("Log parse rule already exists.");
        }
        this.parseRules[rule.name] = rule;
        this.startParsingLogCore();
    }
    startParsingLogCore() {
        this.$deviceLogProvider.on(constants_1.DEVICE_LOG_EVENT_NAME, this.processDeviceLogResponse.bind(this));
    }
    processDeviceLogResponse(message, deviceIdentifier, devicePlatform) {
        const lines = message.split("\n");
        _.forEach(lines, (line) => {
            _.forEach(this.parseRules, (parseRule) => {
                if (!devicePlatform ||
                    !parseRule.platform ||
                    parseRule.platform.toLowerCase() === devicePlatform.toLowerCase()) {
                    const matches = parseRule.regex.exec(line);
                    if (matches) {
                        parseRule.handler(matches, deviceIdentifier);
                    }
                }
            });
        });
    }
}
exports.LogParserService = LogParserService;
__decorate([
    (0, decorators_1.cache)()
], LogParserService.prototype, "startParsingLogCore", null);
yok_1.injector.register("logParserService", LogParserService);
