var myApp = angular.module('myApp');

myApp.controller('FetchreviewsController', ['$scope', '$http', '$location', '$routeParams', '$route', '$interval', function($scope, $http, $location, $routeParams, $route, $interval){
	console.log('FetchreviewsController loaded...');

	$scope.page = 0;
	$scope.nextpage = false;
	var promise;
	$scope.loading = false;

	$scope.getDownloadInfo = function(){
		var id = $routeParams.id;
		$scope.loading = true;
		$http.get('/crawler/getDownloadInfo/'+id).then(function(response){
			$scope.loading = false;
			$scope.app = response.data;
			if($scope.app.reviews.length % 40 == 0) {
				$scope.page = $scope.app.reviews.length/40;
			} else {
				$scope.page = Math.ceil($scope.app.reviews.length/40);
			}
			if($scope.page < 51) {
				$scope.checkNext();
			}
		});
	}

	$scope.checkNext = function(){
		var id = $routeParams.id;
		$scope.loading = true;
		$http.get('/crawler/apps/'+id+"/reviews/?page="+$scope.page).then(function(response){
			$scope.loading = false;
			if(response.status == 400) {
				$scope.reviews = {results:[]};
			} else {
				$scope.reviews = response.data;
			}
		}).catch(function() {
			$scope.reviews = {results:[]};
			$scope.loading = false;
		});
	}

	$scope.downloadNext = function(){
		var id = $routeParams.id;
		$scope.loopRequest(id);
	}

	$scope.loopRequest = function(id) {
		$scope.loading = true;
		$http.get('/crawler/fetchReview/'+id+"/?page="+$scope.page).then(function(response){
			$scope.loading = false;
			if(response.status == 400) {
				$scope.reviews = {results:[]};
			} else if($scope.app.reviews.length == response.data.reviews.length) {
				$scope.reviews = {results:[]};
			} else {
				$scope.app = response.data;
				$scope.page++;
				if($scope.page < 51)
				{
					$scope.loopRequest(id);
				} else {
					$scope.reviews = {results:[]};
				}
			}
		}).catch(function() {
			$scope.reviews = {results:[]};
			$scope.loading = false;
		});
	}

}]);