var angular = require('cla_angular');

/**
 * Datatables rows per page control
 *
 *
 */
(function () {
	'use strict';

	var moduleName = 'cla.core.datatable'; var module;
	try { module = angular.module(moduleName); }
	catch(err) { module = angular.module(moduleName, []); }

	// dependencies
	module.directive('claDtPerPage', PerPage);
	PerPage.$inject = ['dtService'];

	/**
	 *
	 * @param dtService
	 * @constructor
	 */
	function PerPage(dtService) {
		var directive = {
			controller: controller,
			controllerAs: 'controller',
			replace: true,
			restrict: 'E',
			scope: {
				options: '=',
				table: '@',
				per: '@'
			},
			templateUrl: '/interface_default/common/datatable/control/perpage.html'
		};
		directive.controller.$inject = ['$scope'];

		return directive;
		//////////////////


		/** directive controller */
		function controller($scope) {
			var ctl = this;

            this.$onInit = function() {
                ctl.options = [5, 10, 50, 100];
                ctl.per = parseInt($scope.per) || 10;
                ctl.update = update;

                ctl.myService = dtService.get($scope.table);

                init();
            };

			function init() {
				// override defaults
				if ($scope.options && $scope.options.length) {
					ctl.options = $scope.options;
					ctl.per = $scope.options[0];
				}

				// update service
				ctl.myService.per = ctl.per;

				// if datatable is already initialized, make sure we update the per-page property
				if (ctl.myService.datatable) {
					ctl.myService.perPage(ctl.per);
				}
			}

			/**
			 * Update data-table
			 */
			function update() {
				ctl.myService.perPage(ctl.per);
			}
		}
	}
}());
