define(['../app', '../html/config_table_directive.html'], function (app, template) {
    tableController.$inject = ['restCollection', 'growl.service'];

    function tableController(restCollection, growl) {
        var ctrl = this;

        this.$onInit = function() {
            ctrl.hasLoaded = false;
            ctrl.filterText = '';

            restCollection.getAll().then(function () {
                ctrl.model = restCollection.items;
                ctrl.hasLoaded = true;
            });
            ctrl.isSaving = false;

            Object.defineProperty(ctrl, 'buttonText', {
                get: function () {
                    if (ctrl.isSaving)
                        return "Saving...";
                    else
                        return "Save"
                }
            });
        };

        ctrl.save = function ($event) {
            $event.preventDefault();
            ctrl.isSaving = true;

            restCollection.saveAll(ctrl.model).then(function ($response) {
                ctrl.model.length = 0;
                for (var i = 0; i < restCollection.items.length; ++i)
                    ctrl.model.push(restCollection.items[i]);
                growl.showSuccess("Configuration saved");
                ctrl.isSaving = false;
            }, function ($response) {
                if (response.data !== null)
                    growl.showError($response.data.message);
                else
                    growl.showError("Could not contact server");
                ctrl.isSaving = false;
            });
        };
    }

    app.directive('configTable', function () {
        return {
            restrict: 'E',
            replace: true,
            bindToController: true,
            controllerAs: 'ctrl',
            templateUrl: template,
            controller: tableController
        }
    });

});
