'use strict';

/**
 * Broadcast module used for working with pager.
 * Including:
 *   Pager
 */

angular.module('system.services.pager', [
    'config.services'
])
    .service('Pager', [
        'Config',
        function(Config) {

            function Pager(data) {

                this.page = data.page;
                this.size = data.size || 10;
                this.total = data.total;

                this.calculate = function() {
                    var page = this.page || 1;
                    this.from = parseInt((page - 1) * this.size) + 1;
                    this.to = (this.from + this.size) - 1;
                    if (this.to > this.total)
                        this.to = this.total;
                };

                this.canPrev = function() {
                    var page = this.page || 1;
                    return page > 1;
                };

                this.canNext = function() {
                    var page = this.page || 1;
                    return (page * this.size) < this.total;
                };

                this.prev = function() {
                    if (!this.page)
                        this.page = 1;
                    this.page--;
                    this.calculate();
                    return this;
                };

                this.next = function() {
                    if (!this.page)
                        this.page = 1;
                    this.page++;
                    this.calculate();
                    return this;
                };
            }

            var create = function(data) {
                if (!data)
                    throw new Error("Pager > create(): method must receive non-nullable and non-undefined data");

                if (isNaN(data.total))
                    throw new Error("Pager > create(): property 'data.total' must be defined and must be a number");

                var pager = new Pager(data);
                pager.calculate();
                return pager;
            };

            return {
                create: create
            };
        }
    ]);