backupApp.directive('settingSftpServerConfig', function (gettextCatalog) {
    return {
        restrict: 'E',
        scope: {
            uri: '=uri',
            folderPathPrefix: '=',
            isValid: '=',
            canChangeConfig: '='
        },
        templateUrl: 'templates/settings/sftp-server-config.html?v=1.0.3.1',
        controller: function ($scope, $routeParams, AppService, AppUtils, BackupConnectionService, BackupService, SystemInfo, EditUriBackendConfig, DialogService) {
            const scope = $scope;

            const reparseuri = function () {

                if (!scope.uri)
                {
                    return;
                }

                scope.ServerConfig = BackupService.reparseuri(scope.uri, scope.folderPathPrefix, scope.DefaultBackend, scope.SystemInfo.GroupedBackendModules);
                scope.ServerConfig.Path = '';
            };

            
            scope.$watch('uri', reparseuri);
            scope.SystemInfo = SystemInfo.watch($scope, function () {
                for (var n in scope.SystemInfo.GroupedBackendModules)
                    if (scope.SystemInfo.GroupedBackendModules[n].Key == EditUriBackendConfig.defaultbackend)
                        scope.DefaultBackend = scope.SystemInfo.GroupedBackendModules[n];

                reparseuri();
            });

            scope.changeConfiguration = () => scope.isValid = false;
            scope.testConnection = async function () {
                scope.Testing = true;

                const opts = {};
                EditUriBackendConfig.merge_in_advanced_options(scope.ServerConfig, opts);

                if (!scope.ServerConfig.folderPathPrefix.endsWith('/'))
                {
                    scope.ServerConfig.folderPathPrefix += '/';
                }

                const serverConfig = new ServerConfig(
                    'ssh',
                    scope.ServerConfig.Server,
                    scope.ServerConfig.Port,
                    scope.ServerConfig.folderPathPrefix,
                    AppUtils.encodeDictAsUrl(opts),
                    false,
                )
                try {
                    const res = await BackupConnectionService.performConnectionTest(serverConfig, $routeParams.backupid);
                    scope.folderPathPrefix = scope.ServerConfig.folderPathPrefix;
                    scope.uri = res;
                    reparseuri();
                    $scope.isValid = true;
                }finally {
                    scope.Testing = false;

                }
            };;
        }
    }
});