angular.module('app').service('DirPickerService', function ($rootScope, $q, BackendService, L) {

    this.loadRootItems = function (tree, callback) {
        var url = "dirs/listdir?id=0&token=" + BackendService.getToken();

        instance.rootItemsLoading = true;

        BackendService.getPromise(url, null, "GET").then(function (result) {
            if (result.data.success) {
                rootItems = result.data;
                instance.rootItemsLoading = false;
                instance.rootItemsLoaded = true;

                tree.loadJson(rootItems);
                callback();
            } else {
                $rootScope.showError(L.tsq("Loading directory picker root folders failed.") + " " + result.data.error);
                instance.rootItemsLoading = false;
            }
        });
    }

    this.loadItemsForId = function (id, callback) {
        var url = "dirs/listdir?token=" + BackendService.getToken() + "&id=" + id;

        BackendService.getPromise(url, null, "GET").then(function (result) {
            if (result.data.success) {
                //console.error(result.data);
                callback(result.data);
            } else {
                $rootScope.showError(L.tsq("Loading directory picker folders failed.") + " " + result.data.error);
            }
        });
    }

    this.getRootItems = function () {
        return rootItems;
    }

    this.getFilePath = function (id) {
        var deferred = $q.defer();

        BackendService.getPromise('dirs/getFilePath', {
            id: id
        }, "GET").then(function (result) {
            if (result.data.success && result.data.filePath) {
                deferred.resolve({
                    filePath: result.data.filePath.replace(/\\/g, "/"), //replace backslashes
                    success: true
                });
            } else deferred.resolve({
                success: false
            });
        });

        return deferred.promise;
    }

    this.getFilePaths = function (ids) {
        var deferred = $q.defer();

        //console.error(ids);

        BackendService.getPromise('dirs/getFilePaths', {
            ids: ids
        }, 'POST').then(function (result) {
            if (result.data.success && result.data.filePaths) {
                deferred.resolve({
                    filePaths: result.data.filePaths,
                    success: true
                });
            } else deferred.resolve({
                success: false
            });
        });

        return deferred.promise;
    }


    var instance = this;
    var rootItems;

    this.rootItemsLoading = false;
    this.rootItemsLoaded = false;

});