'use strict';

angular.module('shoprApp')
  .controller('BookrCtrl', function ($scope, localStorageService, Auth, $http, $routeParams, $location) {
			
		$scope.Auth = Auth;
		//$scope.books = Auth.getCurrentUser().books;
		$scope.mySubs = Auth.getCurrentUser().books;
 						

		function getById(books, id) {
			for(var b in books) {
				if(books[b]._id === id)
					return books[b];
			}
		}

  function loadMore(book) {
										
			var page = book.recent[book.recent.length-book.pageIndex-1];
				if(page && !page.src) 


				var forward = book.recent[book.recent.length-book.pageIndex];
				if(forward && !forward.src) {
					$http.get('/api/pages/'+book._id+'/'+forward.issue).success(function(fullPage) {
				  for(var k in fullPage[0]) forward[k]=fullPage[0][k];
		  		setTimeout(function(){ $scope.$digest(); }, 500);			
				 });
				}

				var back = book.recent[book.recent.length-book.pageIndex-2];
				if(back && !back.src) {
					$http.get('/api/pages/'+book._id+'/'+back.issue).success(function(fullPage) {
				  for(var k in fullPage[0]) back[k]=fullPage[0][k];
		  		setTimeout(function(){ $scope.$digest(); }, 500);			
				 });
				}



		}

		function init(book, pageIndex) {
	
			book.pageIndex = pageIndex;
			$scope.$watch(function(){ return this.pageIndex; }.bind(book), function(newValue, oldValue){
											
											console.log(this);
			 loadMore(this);
			 //	$location.path('/bookr/'+this._id+'/'+this.pageIndex, false);
				var elm = $('book[ng-id="'+this._id+'"]')[0];
				elm && $('html, body').animate({ scrollTop: elm.offsetTop }, 450);

			}.bind(book));
			$scope.books.push(book);

		}

		function pad(books) {
	for(var b in books) {

			var book = books[b];
			console.log(book);
			var recentLength = book.recent.length;
 	 for(var i = 0; i < book.count-recentLength; i++)
 		  book.recent.push({_id:book._id+'_'+(book.count-(recentLength+1)-i), issue:book.count-(recentLength+1)-i});

					console.log(book);

		}


}

		var books = [$routeParams];
  $scope.books = [];
		for(var b in books) {

			var book = getById($scope.mySubs, books[b].book);
			if(!book) {
				var page = books[b].page;
				$http.get('/api/books/'+books[b].book).success(function(book){ 
												
					pad([book]);
					console.log(book);
					$scope.mySubs.push(book); 
					init(book, page);
			console.log('wtf?');
			
				});
				continue;
			}

			init(book, parseInt(books[b].page));
		 
		}

		});


{
					$http.get('/api/pages/'+book._id+'/'+page.issue).success(function(fullPage) {
				  for(var k in fullPage[0]) page[k]=fullPage[0][k];
		  		setTimeout(function(){ $scope.$digest(); }, 500);			
				 });
				}