/**
 * Service
 */
FanSportsApp.factory('GroupsService', [ '$http', function ($http) {
    var Grid = {
        isLoading  : false,
        items      : [],
        queryString: {
            q: '',  // Query
            f: '',  // Filter
            s: ''   // Sort
        },
        pagination : {
            currentPage: 1,
            pageSize   : 20
        },
        results    : {
            totalItems: null,
            totalPages: null
        },
        call       : function (hasAll, hasNone) {
            var query = '';
            hasAll = typeof hasAll !== 'undefined' ? hasAll : false;
            hasNone = typeof hasNone !== 'undefined' ? hasNone : false;

            Grid.isLoading = true;

            query += 'q=' + Grid.queryString.q;
            query += Grid.queryString.f != '' ? ('&' + Grid.queryString.f) : '';
            query += Grid.queryString.s != '' ? ('&' + Grid.queryString.s) : '';
            query += Grid.pagination.pageSize > 0 ? '&l=' + Grid.pagination.pageSize : '';
            query += '&p=' + Grid.pagination.currentPage;

            $http({
                method: 'GET',
                url   : SportsFanPlayer.basePath + '/groups/rest?' + query
            }).then(function (data) {
                Grid.items = data.data.response.data.entries;

                var oscar = {};

                if (hasNone) {
                    oscar = {
                        id  : null,
                        name: 'None'
                    };
                    Grid.items.unshift(oscar);
                }

                if (hasAll) {
                    oscar = {
                        id  : 0,
                        name: 'All Groups'
                    };
                    Grid.items.unshift(oscar);
                }

                Grid.results = {
                    totalItems: data.data.response.data.pagination.totalItems,
                    totalPages: data.data.response.data.pagination.totalPages
                };


                Grid.isLoading = false;
            });
        },
        refresh    : function () {
            Grid.queryString = {
                q: '',
                f: '',
                s: ''
            };
            Grid.pagination = {
                currentPage: 1,
                pageSize   : 20
            };
            Grid.call();
        },
        selectPage : function () {
            Grid.call();
            return false;
        }
    };

    return {
        grid: Grid
    };
} ]);
