angular.module("app").directive("saveFileDialog", function($rootScope, L) {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        templateUrl: "../app/directives/saveFileDialog/saveFileDialog.html",
        scope: {
            title: '@',
            popupId: '@',
            pathKey: '@',
            fileExtension: '@',
            fileName: '=',
            onSave: '&'
        },
        link: function (scope, element, attrs) {

            scope.openLastDir = function(){
                $rootScope.showFilePicker(L.tsq('Select target folder'), scope.pathKey, false, false, null, scope.fileExtension, null, function(path){
                    scope.selectedFolder = path;
                });
            }

            scope.onSaveFile = function(form){
                if(form){
                    scope.errors = validate(form);
                    if(scope.errors){
                        return;
                    }
                }

                if(!scope.selectedFolder) {
                    $rootScope.showError(L.tsq('Please choose a directory to save the file.'));
                    return;
                }

                if(scope.onSave){
                    var path = scope.selectedFolder + '/' + scope.newFile.name;
                    path = (valueFilled(scope.fileExtension) && !path.endsWith('.'+scope.fileExtension))  ? path + '.' + scope.fileExtension : path;
                    scope.onSave({path: path});
                }
            }

            var destroyFileNameWatch = scope.$watch('fileName', function(newValue, oldValue){
                if(newValue){
                    scope.newFile.name = newValue;
                }
                else scope.newFile.name = '';
            });

            scope.$on("$destroy", function(){
                destroyFileNameWatch();
            });

            scope.folderPicker = {};
            scope.newFile = { name: scope.fileName || '' };

        }
    }
});