window.rcmail && window.rcmail.addEventListener('init', function() {
    if (rcmail.env.task === 'settings'
        && rcmail.env.action === 'plugin.inbox_keys') {
        if (rcmail.gui_objects.keyslist) {
            rcmail.inbox_keys_list = new rcube_list_widget(
                rcmail.gui_objects.keyslist,
                {multiselect: true, draggable: false, keyboard: true});
            rcmail.inbox_keys_list
                .addEventListener('select', list => rcmail.inbox_keys_select(list))
                .addEventListener('keypress',
                    list => rcmail.list_keypress(list, {del: 'plugin.inbox_keys_delete'}))
                .init()
                .focus();
        }

        rcmail.register_command('plugin.inbox_keys_generate', () => rcmail.inbox_keys_generate(), true);
        rcmail.register_command('plugin.inbox_keys_import', () => rcmail.inbox_keys_import(), true);
        rcmail.register_command('plugin.inbox_keys_delete', () => rcmail.inbox_keys_delete(), false);
    }
});

rcube_webmail.prototype.inbox_keys_select = function(list) {
    this.enable_command('plugin.inbox_keys_delete', list.get_selection().length > 0);
};

rcube_webmail.prototype.inbox_keys_generate = function() {
    // TODO: passphrase prompt
    var comment = 'Generated ' + (new Date()).toLocaleDateString();
    var generating_message = this.display_message(
        this.get_label('inbox_settings.generating_key'), 'loading');
    openpgp.generateKey(
        {
            type: 'ecc',
            curve: 'curve25519',
            userIDs: this.env.userIDs.map(
                identity => ({name: identity.name, email: identity.email})),
            format: 'armored'
        }).then(generated => {
            this.hide_message(generating_message);
            var lock = this.display_message(
                this.get_label('inbox_settings.importing_key'), 'loading');
            this.addEventListener('responseafter', () => {
                location.href =
                    'data:application/pgp-keys;base64,' + btoa(generated.privateKey);
                this.reload(1500);
            });
            this.http_post(
                'plugin.inbox_keys_import',
                {import: true, refresh: false, key_data: generated.publicKey, comment},
                lock);
        });
};

rcube_webmail.prototype.inbox_keys_import = function() {
    this.goto_url('plugin.inbox_keys_import');
};

rcube_webmail.prototype.inbox_keys_delete = function() {
    var keys = this.inbox_keys_list.get_selection();
    if (!keys.length) return;

    this.confirm_dialog(
        this.get_label('inbox_settings.confirm_delete_key'),
        'delete',
        function(_evt, ref) {
            var lock = ref.display_message(
                ref.get_label('inbox_settings.deleting_key', 'loading'));
            ref.addEventListener('responseafter', () => ref.reload(1500));
            ref.http_post('plugin.inbox_keys_delete', {keys}, lock);
        });
};
