Source: reporter/information_source.js

import { Reporter } from './reporter.js';
import { EventEmitter } from '../event_emitter.js';
import { v4 as uuid } from '../../node_modules/uuid/dist/esm-browser/index.js';
import { checkPropTypes, copyProps, UUIDRegex } from '../lib.js';


/** Informer */

class InformationSource extends EventEmitter {

    /**
     * @param {Reporter} reporter
     * @param {Object} [settings]
     * @param {UUID} [settings.id]
     * @param {string} [settings.slug]
     * @param {string} [settings.name]
     */

    constructor(reporter, settings = {}) {

        if (!(reporter instanceof Reporter)) {
            throw new Error('No reporter');
        }

        checkPropTypes(
            settings,
            {},
            {
                id: UUIDRegex,
                name: 'string',
            }
        );

        super();

        /** @type {UUID} */

        this.id = settings.id || uuid();


        /** @type {string} */

        this.slug = settings.slug || this.id.substr(0,4);


        /** @type {string} */

        this.name = settings.name || '';


        /** @type {string} */

        this.label = `${this.constructor.name} ${this.name || this.slug}`;


        /**
         * @protected
         * @type {Reporter}
         */

        this._reporter = reporter;


        /**
         * @param {Object} log
         * @param {string} log.msg
         * @param {SyslogLevel} [log.level]
         */

        this.report = ({ msg, level = 'debug' }) =>
            reporter.report({
                msg,
                level,
                time: new Date().getTime(),
                source: {
                    id: this.id,
                    name: this.name,
                    type: this.constructor.name
                }
            });


    }

    static uuid() {
        return uuid();
    }

    destroy() {
        this.removeAllListeners();
        if ( typeof super.destroy === 'function' ) {
            super.destroy()
        }
    }

}

export { InformationSource };