angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope,$ionicPopup,$http, $database, $timeout,$rootScope, $cordovaFileTransfer,$cordovaFile,$ionicLoading,$state,$filter,$ionicModal,$ionicPlatform,$location) {
  

    
	$scope.resetdb = function() {
		$database.setInitialRun(0);
	}

  // Open our new task modal
  $scope.downloadImages = function() {
    $state.go('imagedownload');
  };

  
  
})

.controller('ChatsCtrl', function($scope,$ionicPopup,$http, $database,$window, $timeout,$rootScope, $cordovaFileTransfer,$cordovaFile,$ionicLoading,$state,$filter,$ionicModal,$ionicFilterBar) {
  
   var filterBarInstance;
   
   //View wird zum ersten mal geladen
   $scope.$on( "$ionicView.loaded", function( scopes, states ) {
   		$scope.items=[];
   });



   $scope.$on( "$ionicView.enter", function( scopes, states ) {
      if ($scope.items.length===0){
      	$scope.show($ionicLoading);
      	$timeout(fill_list, 1000);
      }
    });



$scope.showFilterBar = function () {
      filterBarInstance = $ionicFilterBar.show({
        items: $scope.items,
        update: function (filteredItems, filterText) {
          $scope.items = filteredItems;
          if (filterText) {
            console.log(filterText);
          }
        }
      });
    };

    $scope.refreshItems = function () {
      if (filterBarInstance) {
        filterBarInstance();
        filterBarInstance = null;
      }

      $timeout(function () {
        fill_list();
        $scope.$broadcast('scroll.refreshComplete');
      }, 1000);
    };

function fill_list(){
  
  $database.getAllPokemon().then(function (result) {

    if(result.length>0){
      for(i=0;i<result.length;i++){
        $scope.items.push(result[i]);
      }
    } 
    else {
      $scope.items=[];
    }
  });
  $scope.hide($ionicLoading);
}


$scope.show = function() {
    $ionicLoading.show({
      template: '<p>Lade...</p><ion-spinner></ion-spinner>'
    });
  };

$scope.hide = function(){
        $ionicLoading.hide();
};


})


.controller('InitCtrl', function($scope, $ionicPlatform, $database,$state) {

	$ionicPlatform.ready(function() { 

   	 $database.isInitialRun().then(function (result) {
     	
     	if (result==1) {
        	$state.go('tab.dash');
    	}
    	else{
    		$state.go('firstrun');	
    	}

	  });

	});

})


.controller('FirstRunCtrl', function($scope,$ionicSlideBoxDelegate,$database,$state) {


$scope.options = {
  loop: false,
  effect: 'fade',
  speed: 500,
}

$scope.$on("$ionicSlides.sliderInitialized", function(event, data){
  // data.slider is the instance of Swiper
  $scope.slider = data.slider;
});

$scope.$on("$ionicSlides.slideChangeStart", function(event, data){
  console.log('Slide change is beginning');
});

$scope.$on("$ionicSlides.slideChangeEnd", function(event, data){
  // note: the indexes are 0-based
  $scope.activeIndex = data.activeIndex;
  $scope.previousIndex = data.previousIndex;
});

	$scope.firstruncomplete = function() {
		$database.setInitialRun(1);
		$state.go('tab.dash');
	};

})


.controller('ImageDownloadCtrl', function($scope, $database, $timeout, $cordovaFileTransfer,$cordovaFile,$state,$ionicPlatform) {
  

  $scope.progressval = 0;
  $scope.currentfile = '';
  $scope.progressprozent = 0;
  $scope.DownloadisVisible=true;
  $scope.AbbrechenisVisible=false;
  $scope.startdownloadtimer=false;

  // Open our new task modal
  $scope.downloadImages = function() {
  $scope.startdownloadtimer=true;

  $scope.DownloadisVisible=false;
  $scope.AbbrechenisVisible=true;

  //$ionicPlatform.ready(function() { 
    //$scope.taskModal.show();
	var baseurl = "http://assets.pokemon.com/assets/cms2/img/pokedex/full/";
	var url="";
	var filename="";
	var targetPath = "";
	var downloadprogress = 0;
	var pokedexid=1;
  var downloadinprogress=false;
  

    //Ordner erstellen auf SD-Karte
    $cordovaFile.createDir(cordova.file.externalRootDirectory, "PokedexHelperBilder", false)
        .then(function (success) {
    	    // success
    	    console.log('Erfolg bei Ordnererstellung. ' + success);
        }, function (error) {
            // error
            console.log('Error bei Ordnererstellung. ' + error);
     	});

    function downloadimage(){
      downloadinprogress=true;
      filename=pokedexid + ".png";
      
      if (filename.length==5){
        filename='00' + filename;
      }

      if (filename.length==6){
        filename='0' + filename;
      }
    
      url=baseurl;
      url=encodeURI(url + filename);
      targetPath = cordova.file.externalRootDirectory + "/PokedexHelperBilder/" + filename;

      //Bild Download
      $cordovaFileTransfer.download(url, targetPath, {Connection: "close"}, true).then(function (result) {
            $scope.currentfile=filename;
            $database.setPokemonImage(targetPath,pokedexid);
            console.log(filename + ' heruntergeladen.' + result);
            pokedexid=pokedexid + 1;
            console.log(result);
            downloadinprogress=false;
          }, function (error) {
            console.log('Error. ' + error.code + ' ' + error.constant);
          }, function (progress) {
            //downloadprogress=(progress.loaded / progress.total) * 100;
            $scope.progressprozent = Math.round(pokedexid / 721 * 100);
            $scope.progressval = pokedexid;
            $scope.currentfile=filename; //+ downloadprogress;
          });
      console.log(pokedexid);

      if (pokedexid<721){
        downloadtimer();
      }
      else{
        $scope.progressprozent = 'Download abgeschlossen! ' + $scope.progressprozent;
        $scope.DownloadisVisible=true;
        $scope.AbbrechenisVisible=false;
      }

      if (  $scope.startdownloadtimer==false){
        $scope.progressprozent = 'Download Abgebrochen! ' + $scope.progressprozent;
      }
  

    }

	//});

  function downloadtimer(){
    if ($scope.startdownloadtimer==true){


    $timeout(function(){
      if (downloadinprogress==false){
        downloadimage();
        console.log("downinprogress ist false");
      }else{
        console.log("downinprogress ist true");
        downloadtimer();
      }
     }, 500);
    }
  }
  downloadtimer();
  };


$scope.downloadabbrechen = function() {
  $scope.DownloadisVisible=true;
  $scope.AbbrechenisVisible=false;
  $scope.startdownloadtimer=false;
};  
  
})

.controller('Dummy', function($scope) {
});


