angular.module('starter').controller('HomeController',['$scope','cities','$localStorage','$ionicPopup','$ionicSideMenuDelegate', function($scope,cities,$localStorage,$ionicPopup,$ionicSideMenuDelegate){
	
	function fromJSONtoLocal(){
		cities.success(function(data){
			//Add data to local storage
			data.forEach(function(entry){
				if(entry.id != undefined){
					var entryName = 'city' + entry.id;

					//this is data from the JSON file
					for(i=0;i < $localStorage.getLength();i++){
						$localStorage.setObject(entryName, entry);
					}
				}
			});
		});
	}

	fromJSONtoLocal();

	function fromLocaltoScope(){
		$scope.cities = [];

		//Push data from local storage to $scope
		for(i=0;i < $localStorage.getLength();i++){
			if($localStorage.key(i).includes('city')){
				var key = localStorage.key(i);
				var city = $localStorage.getObject(key);

				$scope.cities.push(city);
				city.displayed = true;

				//Check if item has no image (has been recently added) and add look for its photo
				var url = 'img/' + city.city.toLowerCase() + '.jpg';
				if(city.image == null){
					if(imageExists(url)){
						$scope.cities[$scope.cities.length-1].image = url;
						city.image = url;
					} else {
						$scope.cities[$scope.cities.length-1].image = 'img/unknown_city.png';
						city.image = 'img/unknown_city.png';
					}
				}

				//Update city in local storage
				$localStorage.setObject(key,city);
			}					
		}
	}

	$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
		fromLocaltoScope();
	});

	$scope.deleteCity = function(item){
		var confirmPopup = $ionicPopup.confirm({
		     title: 'Delete city',
		     template: 'Are you sure you want to delete '+ item.city +'?'
		   });

		   confirmPopup.then(function(res) {
		     if(res) {
		       deleteCity(item);
		     }
		   });
	}

	function deleteCity(item){		
		//Delete from Local Storage
		var cityKey = "city"+item.id;
		for(i=0;i < $localStorage.getLength();i++){
			if($localStorage.key(i) == cityKey){
				$localStorage.removeItem(cityKey);
			}
		}

		//Delete from scope
		$scope.cities.forEach(function(entry,i){
			if(entry.id == item.id){
				$scope.cities.splice(i,1);
			}
		});
	}

	function imageExists(src) {
	  var img = new Image();
	  img.onload = function() {
	    return true;
	  };
	  img.onerror = function() {
	    return false;
	  };

	  img.src = src; // fires off loading of image
	}

	$scope.leftToggle = function(){
		$ionicSideMenuDelegate.toggleLeft();
	}

	$scope.listCanSwipe = true;
}]);