backupApp.service('BackupService', function($location, $rootScope, $timeout, $cookies, AppService, AppUtils, BackupList, CaptchaService, DialogService, gettextCatalog) {
    let backupService = this;
    
    this.DeleteBackup = function(id) {
        let backup = BackupList.lookup[id];

        DialogService.dialog(gettextCatalog.getString('Export configuration'), gettextCatalog.getString('If you want to use the backup later, you can export the configuration before deleting it'), [gettextCatalog.getString('Cancel'), gettextCatalog.getString('Export'), gettextCatalog.getString('Delete')], function(ix) {
            if (ix == 1) {
                backupService.ExportBackup(id);
            }
            else if (ix == 2) {
                deleteBackup(backup.Backup);
            }
        });
    }

    this.ExportBackup = function (BackupID) {        
        let dlIframe = document.createElement('iframe');
        dlIframe.style.display = 'none';
        dlIframe.src = AppService.get_export_url(BackupID, null, true);
        // const fragment = new DocumentFragment();
        // fragment.innerHTML = `<iframe style="display:none" ng-src="=${{DownloadURL}}"></iframe>`;
        document.body.appendChild(dlIframe);
    }

    let deleteBackup = function(backup) {
        DialogService.dialog(gettextCatalog.getString('Confirm delete'), gettextCatalog.getString('Do you really want to delete the backup: "{{name}}" ? (no rollback possible)', {name: backup.Name}), [gettextCatalog.getString('No'), gettextCatalog.getString('Yes')], function(ix) {
            if (ix == 1) {
                catcha(backup);
            }
        });
    }

    let catcha = function(backup) {
        CaptchaService.Authorize(
            gettextCatalog.getString('Confirm delete'), 
            gettextCatalog.getString('To confirm you want to delete all remote files for "{{name}}", please enter the word you see below', {name: backup.Name}),
            'DELETE /backup/' + backup.ID,
            function(token, answer) {
                AppService.delete('/backup/' + backup.ID + '?delete-local-db=true&delete-remote-files=true&captcha-token=' + token + '&captcha-answer=' + answer).then(function() {
                    $location.path('/');
                }, AppUtils.connectionError);
            }
        );
    }
});