/*
 * Tine 2.0
 *
 * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
 * @author      Cornelius Weiß <c.weiss@metaways.de>
 * @copyright   Copyright (c) 2019 Metaways Infosystems GmbH (http://www.metaways.de)
 */

const { retryAllRejectedPromises } = require('promises-to-retry');

Ext.namespace('Tine.OnlyOfficeIntegrator');

Tine.OnlyOfficeIntegrator.Application = Ext.extend(Tine.Tinebase.Application, {

    hasMainScreen: false,

    /**
     * Get translated application title
     *
     * @return {String}
     */
    getTitle: function() {
        return this.i18n._('Only Office Integrator');
    },

    init: function() {
        // report frequency is 0.8 * timeout
        this.reportOpenEditorsTimeout = Tine.Tinebase.configManager.get('tokenLiveTime', 'OnlyOfficeIntegrator') * 800;

        this.isOOWindowRe = new RegExp('^' + Tine.OnlyOfficeIntegrator.OnlyOfficeEditDialog.prototype.windowNamePrefix);

        // register frequent-delayed task
        window.setInterval(_.bind(this.reportOpenEditors, this), this.reportOpenEditorsTimeout);
    },

    reportOpenEditors: function() {
        const keys = [];

        Tine.WindowFactory.windowManager.each((win) => {
            if (String(win.name).match(this.isOOWindowRe) && win.onlyOfficeDocumentKey) {
                _.each(_.split(win.onlyOfficeDocumentKey, ','), _.bind(_.ary(keys.push, 1), keys, _));
            }
        });

        if (keys.length) {
            retryAllRejectedPromises([_.partial(Tine.OnlyOfficeIntegrator.tokenKeepAlive, keys)], {
                maxAttempts: 5, delay: 1200
            });
        }
    }
});
