angular.module("app").directive("directoryPickerModal", function (BackendService, AppService, $rootScope, $timeout, SQConstants) {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        templateUrl: "../app/directives/directoryPickerModal/dirPickerModal.html",
        scope: {
            instance: '=',
            selectButton: '@',
            title: '@',
            onSelect: '=',
            multiselection: '@',
            showFiles: '@',
            currentDir: '@',
            actionType: '@',
            extension: '=',
            fileName: '@',
        },
        link: function (scope, element, attrs, ctrl, transclude) {

            scope.instance.getTree = function () {
                return scope.directoryTree;
            }

            scope.instance.showDialog = function (dirPath) {
                $timeout(function () {        //necessary for the changes to apply 
                    if(window.electron) {
                        const dialogConfig = {
                            filters: [],
                            properties: []
                        };

                        if(scope.showFiles && scope.showFiles=='true') {
                            dialogConfig.title = 'Select a file';
                            dialogConfig.properties.push('openFile');
                        } else {
                            dialogConfig.title = 'Select a directory';
                            dialogConfig.properties.push('openDirectory');
                        }

                        if(scope.multiselection) {
                            dialogConfig.properties.push('multiSelections');
                        }

                        if(scope.extension) {
                            if (typeof scope.extension === 'string') {
                                dialogConfig.filters.push({ 
                                    name: 'Custom File Type', 
                                    extensions: scope.extension.split(',')
                                });
                            } else if (Array.isArray(scope.extension)) {
                                scope.extension.forEach(function(ext) {
                                    dialogConfig.filters.push({ 
                                        name: ext.description, 
                                        extensions: ext.name.split(',')
                                    });
                                });
                            } else if (scope.extension.description && scope.extension.name) {
                                dialogConfig.filters.push({ 
                                    name: scope.extension.description, 
                                    extensions: scope.extension.name.split(',')
                                });
                            }
                        }

                        console.log("Opening file chooser: ", scope.showFiles, scope.currentDir, scope.fileName, scope.extension, dialogConfig);

                        electron.openDialog('showOpenDialog', dialogConfig).then(result => {
                            console.log("File selected", result)

                            if (result.filePaths.length < 1) {
                                return;
                            }

                            scope.onSelect(result.filePaths);
                        });

                    } else { //remote web browser - display JS file chooser
                        if (dirPath) {
                            scope.directoryTree.openDir(dirPath);
                        }
                        else if (scope.actionType) {
                            scope.instance.setPath(scope.actionType);
                        }

                        if (scope.currentDir) {
                            scope.directoryTree.openDir(scope.currentDir);
                        }
                        scope.directoryTree.setMultiSelection(scope.multiselection);
                        showFiles(scope.showFiles);

                        showPopup("#" + attrs.id);
                    }
                }, 0, false);
            }

            function showFiles(showFiles) {
                var data = {
                    showFiles: showFiles,
                    extension: scope.extension ? scope.extension.name : null
                }

                BackendService.getPromise('dirs/settings', data, 'GET').then(function (result) {
                    if (result.data.success) {
                        console.log("DirPicker settings saved.");
                    }
                    else {
                        console.error("Cannot save DirPicker settings. " + result.data.error);
                    }
                });
            }

            scope.onSelectFolder = function () {
                var selectedPaths = scope.directoryTree.getSelectedPaths().then(function (result) {
                    if (result.success) {
                        var filePaths = [];

                        if (result.filePath) {
                            filePaths.push(result.filePath);
                        }
                        else if (result.filePaths) {
                            filePaths = result.filePaths;
                        }
                        else {
                            console.error("Cannot get paths from the request result");
                            return;
                        }

                        setLastFolderUsed(filePaths);

                        if (scope.onSelect) {
                            scope.onSelect(filePaths);
                        }
                        else if (scope.instance.onSelect) {
                            scope.instance.onSelect(filePaths);
                        }
                    }
                    else {
                        console.error("Cannot get selected paths.");
                    }
                });
            }

            /**
             * Sets current directory to path included in settings.
             * If path name isn't found, project folder is used.
             */
            scope.instance.setPath = function (pathName) {
                var path = SQConstants.getSettings()[pathName];

                if (path) {
                    scope.currentDir = path;
                }
                else {
                    var projectsPath = SQConstants.getSettings().projectsPath;
                    SQConstants.getSettings()[pathName] = projectsPath;
                    scope.currentDir = projectsPath;
                }
            }

            function setLastFolderUsed(paths) {
                if (paths.length < 1) {
                    return;
                }

                var path = paths[0];

                var data = {
                    path: path,
                    actionType: scope.actionType
                };

                BackendService.getPromise('dirs/setLastFolderUsed', data, 'GET').then(function (result) {
                    if (result.data.success) {
                        SQConstants.getSettings()[scope.actionType] = result.data.path;
                        console.log("Last folder used saved");
                    }
                    else {
                        console.error("Cannot save last folder. " + result.data.error);
                    }
                });

                SQConstants.getSettings().lastFolderUsed = path;
            }

            element.find('.form-horizontal').append(transclude());

            scope.directoryTree = {};
            scope.dirPickerId = attrs.id + "_tree";
        }
    };
});