"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _1 = require("../../../../../Class/$");
const Semifunctional_1 = require("../../../../../Class/Semifunctional");
const _ids_1 = require("../../../../_ids");
class EventSource_ extends Semifunctional_1.Semifunctional {
    constructor(system) {
        super({
            fi: ['url'],
            fo: ['emitter'],
            i: ['close'],
            o: [],
        }, {
            output: {
                emitter: {
                    ref: true,
                },
            },
        }, system, _ids_1.ID_EVENT_SOURCE);
        this._event_source = null;
        this._pluck = () => {
            if (this._event_source) {
                this._event_source.close();
                this._event_source = null;
            }
        };
    }
    f({ url }, done) {
        const { api: { http: { EventSource }, }, } = this.__system;
        const eventSource = new EventSource(url);
        this._event_source = eventSource;
        eventSource.onerror = (err) => {
            this._pluck();
            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 });
        };
    }
    onIterDataInputData(name, data) {
        if (name === 'close') {
            this._pluck();
        }
    }
}
exports.default = EventSource_;
//# sourceMappingURL=index.js.map