<% macro EntityMeta(name) %>
    $rootScope.title = '<%= name %>';
    if (typeof $routeParams === 'object' && $routeParams.id) {
        $scope.id = $routeParams.id;
    }
    window.skope = $scope;
<% endmacro %>



<% macro SearchForm(params) %>
    $scope.form  = {};

    $scope.search = function (form) {  
        $scope.<%= params.name %>.dataSource.fetch();
    };
<% endmacro %>



<% macro KendoDataSource(params) %>
    $scope.<%= params.name %> = {};
    $scope.<%= params.name %>.count = 0;
    $scope.$parent.dataSourceSearchOptions = {};
    $scope.<%= params.name %>.dataSource = new kendo.data.DataSource({
        transport: {
            read : function (options) {

                if (!$scope.$parent) {
                    return;
                }

                var params = {'offset': options.data.skip, 'limit': options.data.pageSize};

                params.query = $scope.$parent.dataSourceSearch;
                angular.forEach($scope.$parent.dataSourceSearchOptions, function (value, option) {
                    if (angular.isDefined(value) && value != null && value != '') {
                        if (params.query) {
                            if (params.query.length) {
                                params.query += ' ';
                            }
                        } else {
                            params.query = '';
                        }
                        params.query += option + ':' + value
                    }
                });

                if(typeof options.data.sort !== 'undefined'){
                    if(options.data.sort.length>0){
                        params.order = options.data.sort[0].field+' '+options.data.sort[0].dir;
                    }
                    else{
                        params.order = '<%= params.order %> <%= params.direction %>';
                    }
                }

                angular.extend(params, $scope.$eval('<%= params.params | raw %>'));
                angular.extend(params, $scope.form);

                Restangular.all('<%= params.name %>').getList(params).then(function (response) {
                    $scope.<%= params.name %>.count = response.headers()['x-metadata-total'];
                    options.success(response.data);
                }, function (errors) {
                    Message.send('<%= params.errorMessage|default('Error!') %>', 'error');
                });

            }
        },
        schema: {
            total: function (response) {
                return $scope.<%= params.name %>.count;
            }
        },
        pageSize: <%= params.size %>,
        serverPaging: true,
        serverFiltering: true,
        serverSorting: true,
        <% if params.order is defined and params.direction is defined %>
        sort: { field: '<%= params.order %>', dir: '<%= params.direction %>' }
        <% endif %>
    });
    $scope.<%= params.name %>.onDataBound = function(e) {
        var footer = e.sender.pager.element.children().not('.k-pager-refresh, .k-pager-sizes');
        if (parseInt(e.sender.dataSource._total, 10) <= e.sender.dataSource._data.length) {
            footer.hide();
        } else {
            footer.show();
        }
    };
    if ($scope.$parent.watchDataSourceSearch) {
        $scope.$parent.watchDataSourceSearch();
    }
    $scope.$parent.watchDataSourceSearch = $scope.$parent.$watch('dataSourceSearch', function (value, oldVal) {
        if (value != oldVal) {
            $scope.<%= params.name %>.dataSource.read()
        }
    });
    if ($scope.$parent.watchDataSourceSearchOptions) {
        $scope.$parent.watchDataSourceSearchOptions();
    }
    $scope.$parent.watchDataSourceSearchOptions = $scope.$parent.$watch('dataSourceSearchOptions', function (value) {
        if (value) {
            $scope.<%= params.name %>.dataSource.read()
        }
    }, true);

<% endmacro %>



<% macro EntitiesGet(params) %>
    Restangular.one('<%= params.namePlural %>').get().then(function (response) {
        $scope.<%= params.nameSingular %> = response.data.originalElement;
    }, function (errors) {
        Message.send('<%= params.errorMessage|default('Error!') %>', 'error');
    });
<% endmacro %>



<% macro EntityGet(params) %>
    Restangular.one('<%= params.namePlural %>', $scope.id).get(<%= params.params|raw %>).then(function (response) {
        $scope.<%= params.nameSingular %> = response.data.originalElement;
    }, function (errors) {
        Message.send('<%= params.errorMessage|default('Error!') %>', 'error');
    });
<% endmacro %>



<% macro EntityGetList(params) %>
    Restangular.all('<%= params.namePlural %>').getList(<%= params.params|raw %>).then(function (response) {
        $scope.<%= params.nameSingular %> = response.data.originalElement;
    }, function (errors) {
        Message.send('<%= params.errorMessage|default('Error!') %>', 'error');
    });
<% endmacro %>



<% macro EntityCreate(params) %>
    $scope.<%= params.verb|default('submit') %> = function (data) {
        return Restangular.all('<%= params.namePlural %>').post(data).then(function(response) {
            Message.send('<%= params.successMessage|default('Created!') %>', 'success');
            $scope.<%= params.nameSingular %>Errors = null;
            <% if params.return_address %>
            if ($location.path() == '<%= params.return_address %>') {
                window.location.reload();
            } else {
                $location.path('<%= params.return_address %>');
            }
            <% elseif params.return_path %>
            Restangular.oneUrl('<%= params.nameSingular %>', response.headers('location')).get().then(function(response) {
                $location.path('<%= params.return_path %>' + response.data.id);
            });
            <% elseif params.return_history %>
                window.history.back();
            <% endif %>
        }, function (errors) {
            Message.send('<%= params.errorMessage|default('Error!') %>', 'error');
            $scope.<%= params.nameSingular %>Errors = errors.data;
        });
    };
<% endmacro %>



<% macro EntityUpdate(params) %>
    $scope.<%= params.verb|default('submit') %> = function (data) {
        var promise = Restangular.one('<%= params.namePlural %>', $scope.id).patch(data);
        promise.then(function () {
            Message.send('<%= params.successMessage|default('Saved!') %>', 'success');
            $scope.<%= params.nameSingular %>Errors = null;
            <% if params.return_address %>
                $location.path('<%= params.return_address %>');
            <% elseif params.return_path %>
                $location.path('<%= params.return_path %>' + data.id);
            <% elseif params.return_history %>
                window.history.back();
            <% endif %>
            var updateParams = ['slug', 'path'];
            if (updateParams.reduce(function (bool, param) { return bool || data.hasOwnProperty(param); }, false)) {
                Restangular.one('<%= params.namePlural %>', data.id).get().then(function (response) {
                    response = response.data.originalElement;
                    angular.forEach(updateParams, function (param) {
                        if (response.hasOwnProperty(param)) {
                            $scope.<%= params.nameSingular %>[param] = response[param];
                        }
                    });
                });
            }
        }, function (errors) {
            Message.send('<%= params.errorMessage|default('Error!') %>', 'error');
            $scope.<%= params.nameSingular %>Errors = errors.data;
        });
        return promise;
    };
<% endmacro %>



<% macro EntityDelete(params) %>
    $scope.<%= params.verb|default('submit') %> = function () {
        return Restangular.one('<%= params.namePlural %>', $scope.id).remove().then(function() {
            Message.send('<%= params.successMessage|default('Deleted!') %>', 'success');
            $location.path('<%= params.return_path %>');
        }, function (errors) {
            Message.send('<%= params.errorMessage|default('Error!') %>', 'error');
        });
    };
<% endmacro %>



<% macro Upload(params) %>
    $scope.<%= params.nameSingular %>Upload = {};
    $scope.<%= params.nameSingular %>Upload.opts = {
        saveUrl: '<%= params.url %>',
        saveField: '<%= params.namePlural %>',
        autoUpload: true
    };

    $scope.<%= params.nameSingular %>Upload.onSuccess = function (response) {
        Message.send('<%= params.successMessage|default('Uploaded!') %>', 'success');
        if ($scope.<%= params.namePlural %>) {
            $scope.<%= params.namePlural %>.dataSource.fetch();
        }
    };

    $scope.<%= params.nameSingular %>Upload.onError = function (response) {
        Message.send('<%= params.errorMessage|default('Error!') %>', 'error');
    };

    $scope.<%= params.nameSingular %>Upload.onUpload = function (e) {
        var xhr = e.XMLHttpRequest;

        if (xhr) {
            xhr.addEventListener('readystatechange', function (e) {
                if (xhr.readyState == 1) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + Auth.getToken());
                }
            });
        }
    };
<% endmacro %>



<% macro PanelDataService(params) %>

    $scope.$watch(function() { return AssignmentMediator.change; }, function(value, oldValue) {
        if (value == oldValue) {
            return;
        }
        if (angular.isDefined(AssignmentMediator.type)) {
            $scope.panelActive = AssignmentMediator.type;
            //$scope.setDataService(AssignmentMediator.type);
        }
    });
    /*
    $scope.dataService = new DataService();
    $scope.dataProps = {
        uploader: false,
        highlight: null
    };

    $scope.relatedContent = {
    <% for item in params.types %>
        <%= item.namePlural %>: [],
    <% endfor %>
    };

    $scope.switchPanelActive = function(type) {
        if ($scope.dataService.type == type) {
            $scope.panelActive = !$scope.panelActive;
        } else {
            $scope.panelActive = true;
        }
    }

    $scope.setDataService = function(type) {
        if ($scope.dataService.type == type) {
            return;
        }
        $scope.dataService.reset();
        switch (type) {
            <% for item in params.types %>
            case '<%= item.nameSingular %>':
                $scope.dataService.type = '<%= item.nameSingular %>';
                $scope.dataService.api = '<%= url({"entity": item.namePlural}, "api") %>';
                $scope.dataService.setOption('limit', <%= item.limit|default('10') %>);
                $scope.dataService.setOption('offset', <%= item.offset|default('0') %>);
                $scope.dataService.setOption('select',  <% if item.select %>'<%= item.select %>'<% else %>null<% endif %>);
                $scope.dataService.origin = <% if item.hasOrigin %>'<%= params.origin %>-' + $scope.id<% elseif item.origin %>'<%= item.origin %>'<% else %>''<% endif %>;
                $scope.dataService.setOption('origin', <% if item.origin %>'<%= item.origin %>'<% else %>''<% endif %>);
                $scope.dataProps.uploader = <%= item.hasUploader ? 'true' : 'false' %>;
                $scope.dataProps.highlight = $scope.relatedContent.<%= item.namePlural %>;
                break;
            <% endfor %>
        }

        $scope.dataService.get();
    }
    $scope.setDataService('<%= params.defaultType %>');
    */

<% endmacro %>