"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Holder_1 = require("../../../../../Class/Holder");
const _ids_1 = require("../../../../_ids");
class RequestPictureInPicture extends Holder_1.Holder {
    constructor(system) {
        super({
            fi: ['media', 'opt'],
            i: [],
        }, {
            input: {
                media: {
                    ref: true,
                },
            },
        }, system, _ids_1.ID_REQUEST_PICTURE_IN_PICTURE);
        this._exit_picture_in_picture_promise = Promise.resolve();
    }
    async f({ media, opt }, done, fail) {
        const { api: { document: { pictureInPictureElement }, }, } = this.__system;
        await this._exit_picture_in_picture_promise;
        let element;
        try {
            element = await media.requestPictureInPicture();
        }
        catch (err) {
            fail(err.message.toLowerCase());
            return;
        }
        if (pictureInPictureElement === element) {
            fail('media is already displayed picture in picture');
            return;
        }
        const window = await element.requestPictureInPicture();
        this._picture_in_picture = window;
        const leavePnPListener = () => {
            this._picture_in_picture = undefined;
            this.d();
            this._backward('opt');
        };
        element.addEventListener('leavepictureinpicture', leavePnPListener);
        this._unlisten = () => {
            element.removeEventListener('leavepictureinpicture', leavePnPListener);
        };
    }
    d() {
        const { api: { document: { exitPictureInPicture }, }, } = this.__system;
        if (this._unlisten) {
            this._unlisten();
            this._unlisten = undefined;
        }
        if (this._picture_in_picture) {
            this._exit_picture_in_picture_promise = exitPictureInPicture();
            this._picture_in_picture = undefined;
        }
    }
}
exports.default = RequestPictureInPicture;
//# sourceMappingURL=index.js.map