"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const AsyncWorker_1 = require("../../../../AsyncWorker");
const Functional_1 = require("../../../../Class/Functional");
const worker_1 = require("../../../../client/platform/web/port/worker");
const RemoteClient_1 = require("../../../../RemoteClient");
const wrap_1 = require("../../../../wrap");
const _ids_1 = require("../../../_ids");
class Worker extends Functional_1.Functional {
    constructor(system) {
        super({
            i: ['init'],
            o: ['system'],
        }, {
            output: {
                system: {
                    ref: true,
                },
            },
        }, system, _ids_1.ID_WORKER);
        this.addListener('destroy', () => {
            if (this._client) {
                this._client.terminate();
                this._client = undefined;
            }
        });
    }
    f({ init }, done) {
        const { specs, api: { worker: { start }, }, } = this.__system;
        if (!this._client) {
            let worker;
            try {
                worker = start();
            }
            catch (err) {
                done(undefined, err.message);
                return;
            }
            const port = (0, worker_1.workerPort)(worker);
            const client = new RemoteClient_1.RemoteClient(port);
            this._client = client;
        }
        this._client.init({});
        const port = this._client.port();
        const $system = (0, AsyncWorker_1.AsyncWorkerS)(port);
        const system = (0, wrap_1.$wrap)(this.__system, $system);
        done({
            system,
        });
    }
    i() {
        // if (name === 'spec') {
        this._client.invalidate();
        // }
    }
}
exports.default = Worker;
//# sourceMappingURL=index.js.map