"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _1 = require("../../../../../Class/$");
const Holder_1 = require("../../../../../Class/Holder");
const _ids_1 = require("../../../../_ids");
class EventSource_ extends Holder_1.Holder {
    constructor(system) {
        super({
            fi: ['url', 'opt'],
            fo: ['emitter'],
            i: [],
            o: [],
        }, {
            output: {
                emitter: {
                    ref: true,
                },
            },
        }, system, _ids_1.ID_EVENT_SOURCE, 'close');
        this._event_source = null;
    }
    f({ url, opt }, done) {
        const { api: { http: { EventSource }, }, } = this.__system;
        const eventSource = new EventSource(url, opt);
        this._event_source = eventSource;
        eventSource.onerror = (err) => {
            this.d();
            done(undefined, 'error connecting to server');
        };
        eventSource.onopen = (event) => {
            const emitter = new (class EventEmitter__ extends _1.$ {
                addListener(event, listener) {
                    super.addListener(event, listener);
                    const _listener = (event) => {
                        // @ts-ignore
                        listener(event.data);
                    };
                    eventSource.addEventListener(event, _listener);
                    return () => {
                        eventSource.removeEventListener(event, _listener);
                    };
                }
            })(this.__system);
            // @ts-ignore
            done({ emitter });
        };
    }
    d() {
        if (this._event_source) {
            this._event_source.close();
            this._event_source = null;
        }
    }
}
exports.default = EventSource_;
//# sourceMappingURL=index.js.map