"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _1 = require("../../../../../Class/$");
const Holder_1 = require("../../../../../Class/Holder");
const stringify_1 = require("../../../../../spec/stringify");
const _ids_1 = require("../../../../_ids");
class Open extends Holder_1.Holder {
    constructor(system) {
        super({
            fi: ['url', 'target', 'features', 'detached'],
            fo: ['window'],
            i: [],
            o: [],
        }, {
            output: {
                window: {
                    ref: true,
                },
            },
        }, system, _ids_1.ID_OPEN);
    }
    f({ url, target, features, detached }, done) {
        const { api: { window: { open }, }, } = this.__system;
        this._detached = detached;
        const windowFeatures = Object.entries(features)
            .map(([key, value]) => {
            return `${key}=${value}`;
        })
            .join(',');
        const _window = open(url, target, windowFeatures);
        this._window = _window;
        const channel = new (class Channel extends _1.$ {
            constructor() {
                super(...arguments);
                this.__ = ['CH'];
            }
            async send(data) {
                const _data = (0, stringify_1.stringify)(data);
                _window.postMessage(_data, '*');
                return;
            }
        })(this.__system);
        try {
            window.addEventListener('message', (event) => {
                // @ts-ignore
                channel.emit('message', event.data);
            });
        }
        catch (err) {
            done(undefined, err.message);
            return;
        }
        done({
            window: channel,
        });
    }
    d() {
        if (this._window && !this._detached) {
            this._window.close();
            this._window = undefined;
            this._detached = undefined;
        }
    }
}
exports.default = Open;
//# sourceMappingURL=index.js.map