<?php ob_start(); ?>
<div style="position: relative;min-height: 150px;" ng-cloak>
	<div ng-show="ngModel.loading" style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;width: 100%;height: 100%;background: rgba(255,255,255,0.2);display: flex;justify-content: center;align-items: center;z-index: 1000;">
		<md-progress-circular md-mode="indeterminate"></md-progress-circular>
	</div>
	<div>
		<ng-transclude></ng-transclude>
	</div>
	<pagination length="ngModel.nbrPage" page="ngModel.page" ng-page="ngModel.loadData(page)"></pagination>
</div>
<?php $tpl=ob_get_clean(); ?>
<script>
	app.directive("apiData", [function () {
		return {
			restrict: 'EA',
			scope:{ngModel:"=?",api:"@",initItem:"=?",filter:"=",onResponce:"&?"},
			template:<?= json_encode($tpl) ?>,
			transclude:true,
			link: function ($scope, iElement, iAttrs) {
				var getScrollParent = function (node) {
				  if (!node) {
				    return null;
				  }
				  if (node.scrollHeight > node.clientHeight) {
				    return node;
				  } else {
				    return getScrollParent(node.parentNode);
				  }
				}
				if(!$scope.ngModel) $scope.ngModel = {};
				$scope.ngModel.data = [];
				$scope.ngModel.loading = false;
				$scope.firstload = true;
				$scope.ngModel.loadData = function(page){
					if(!page) page = $scope.ngModel.page;
					$scope.ngModel.loading = true;
					api($scope.api,{page:page,filter:$scope.filter},function(rep){
						for(var x in rep){
							$scope.ngModel[x] = rep[x];
						}
						$scope.ngModel.data = rep.data;
						for (var i = $scope.ngModel.data.length - 1; i >= 0; i--) {
							(function(item,$scope){
								$scope.initItemBase(item);
							})($scope.ngModel.data[i],$scope);
						}
						$scope.ngModel.page = page;
						$scope.ngModel.nbrPage = rep.nbrPage;
						$scope.ngModel.total = rep.total;
						$scope.ngModel.loading = false;
						if(iElement && !$scope.firstload){
							$(getScrollParent(iElement[0])).animate({scrollTop: iElement.offset().top-200 }, 300);
						}
						$scope.firstload = false;
						if($scope.onResponce) $scope.onResponce({mdl : $scope});
						$scope.$apply();
					});
				}
				$scope.initItemBase = function(item){
					if ($scope.initItem) {
						$scope.initItem(item);
					}
				}
				$scope.ngModel.initItemBase = $scope.initItemBase;
				$scope.ngModel.loadData(1);
			}
		};
	}]);
</script>