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

/*======================================
=            AppCtrl - Main            =
======================================*/

.controller('AppCtrl', function($scope, $ionicModal, $timeout,  $ionicPopup, $ionicViewService, $location) {



  $scope.lock = {};

  var newNotes = false;
  $scope.logged = false;

  var userStr = window.localStorage['userInfo'] || null;
  if(userStr !== null)
    $scope.userData = JSON.parse(userStr);
  else
    $scope.userData = null;

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/Aouth.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });



    if((window.localStorage['userInfo'] || null) === null )
      $scope.isLoggedIn = false;
    else
      $scope.isLoggedIn = true;

  

  // Triggered in the Aouth modal to close it
  $scope.closeAouth = function() {
    $scope.modal.hide();
  };

  // Aouth for Grades
  $scope.Aouth = function() {
    console.log("Clicked GoOn - password enterd: "+ $scope.lock.password + "\nThe logs pass is: "+window.localStorage['password']);

    if($scope.lock.password === (window.localStorage['password'] || null)){ //ok
      $scope.lock.password = "";
      $scope.modal.hide();
      $ionicViewService.nextViewOptions({
      disableBack: true });

      $location.path( "/app/grades" );
    }else{
      var alertPopup = $ionicPopup.alert({
                title: 'סיסמה שגוייה',
                template: 'טעות בסיסמה'
                });
        alertPopup.then(function(res) {
            $scope.modal.hide();
            });
    }
  };

  
  


  $scope.logout = function(){
    localStorage.clear();
    navigator.app.exitApp();
  };


  $scope.openGrades = function(){
    var localSettingsStr = window.localStorage['Settings'] || null;
    if (localSettingsStr !== null){
      var isLocked = (JSON.parse(localSettingsStr))[0].val;
    }
    if(isLocked){
      console.log("[JCE] [INFO]: Grades Locked");
      $scope.modal.show();
    }
    else{
      console.log("Unlocked");
      $ionicViewService.nextViewOptions({
      disableBack: true });
      $location.path( "/app/grades" );
    }
  };

  $scope.menuClicked = function(){
    if((window.localStorage['userInfo'] || null) === null ){
      $scope.isLoggedIn = false;
    }else
      $scope.isLoggedIn = true;
  };




})


////////////////////////////////////////////////////////////////

.controller('PlaylistsCtrl', function($scope) {
  $scope.playlists = [
  { title: 'Reggae', id: 1 },
  { title: 'Chill', id: 2 },
  { title: 'Dubstep', id: 3 },
  { title: 'Indie', id: 4 },
  { title: 'Rap', id: 5 },
  { title: 'Cowbell', id: 6 }
  ];
})

.controller('PlaylistCtrl', function($scope, $stateParams) {


})

/*=============================================
=            Grades   - controller            =
=============================================*/




.controller('GradesCtrl', function($scope, $stateParams, $http) {
  var gradesStr = window.localStorage['grades'] || null;
  var fixGrades = new Array;
  var j = 0;
  //console.log(gradesStr);
  if(gradesStr != null){
    grades = JSON.parse(gradesStr);
    for(var i = 0; i < grades.length ; i++){
      console.log("In loop #: "+i);
      console.log(JSON.stringify(fixGrades));
      if( i != 0){
        if(grades[i].subject_code != grades[i-1].subject_code){
          fixGrades.push({
            "subject": grades[i].subject,
            "credits": grades[i].credits,
            "subject_code": grades[i].subject_code,
            "year": grades[i].year,
            "tests": [{
              "moed": grades[i].moed,
              "final_grade": grades[i].final_grade
            }]
          });
          j++;
        }else{
          fixGrades[j-1].tests.push({
            "moed": grades[i].moed,
            "final_grade": grades[i].final_grade
          });
        }
      }else{
        fixGrades.push({
            "subject": grades[i].subject,
            "credits": grades[i].credits,
            "subject_code": grades[i].subject_code,
            "year": grades[i].year,
            "tests": [{
              "moed": grades[i].moed,
              "final_grade": grades[i].final_grade
            }]
          });
        j++;
      }
    }

    console.log(JSON.stringify(fixGrades));

    $scope.grades = fixGrades;
  }


  // $scope.getMedal = function(grade){
  //   if(grade < 55){
  //     return "https://wiki.openttd.org/images/1/10/Face-Sick-120px.png";
  //   }else if( 55<= grade && grade < 70){
  //     return "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcT6UK4UUxagOktpvJR_P433nvOeTDuV3rOxd0Mswo8T-tRueFmN";
  //   }else if( 70<= grade && grade < 80){
  //     return "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRz0_NkZPM9FSymaCqFObwGPQFA9vRGZ82DEM7jfFU6xQ3qLbu8oQ";
  //   }else if( 80<= grade && grade < 95){
  //     return "data:image/jpeg;base64, ";
  //   }else{
  //     return "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRR0zMfWYUcjYyXjGUQY3tDj04rIFfi_CThbaolxTt_38eL1hkFmQ";
  //   }

  //   return "sdfgg";
  // };


})



/*=============================================
=            Settings     - controller        =
=============================================*/




.controller('SettingsCtrl', function($scope, $stateParams, $http) {

  var localSettingsStr = window.localStorage['Settings'] || null;
  if (localSettingsStr === null){
    var settings_list = [ {text:"נעל גיליון ציונים", val: false}];//,      //[0]
                        //{text:"הצג מזג אויר", val: false}   ];   //[1]
    console.log("[JCE] [info]: No settings found!");
  }
  else{
    settings_list = JSON.parse(localSettingsStr);
    console.log("[JCE] [info]: settings found!");
  }

  $scope.settings = settings_list;

  $scope.toggled = function(){
    console.log("[JCE] [info]: Setting Changed");
    window.localStorage['Settings'] = JSON.stringify($scope.settings);
  };



})


/*=============================================
=            Aguda News   - controller        =
=============================================*/




.controller('AgudaCtrl', function($scope, $stateParams, $http) {
  var notesStr = window.localStorage['notes'] || null;
  console.log(notesStr);
  if(notesStr != null)
    $scope.newss = JSON.parse(notesStr);



})


/*=============================================
=            JCE News   - controller            =
=============================================*/




.controller('JCENewsCtrl', function($scope, $stateParams, $http) {
  var notesStr = window.localStorage['notes'] || null;
  console.log(notesStr);
  if(notesStr != null)
    $scope.newss = JSON.parse(notesStr);



})

/*=============================================
=            Calendar - controller            =
=============================================*/




.controller('CalendarCtrl', function($scope, $stateParams, $http) {
  var calendarStr = window.localStorage['calendar'] || null;
  console.log(calendarStr);
  if(calendarStr != null)
    $scope.calendar = JSON.parse(calendarStr);



})


/*=============================================
=            Login Controller                 =
=============================================*/




.controller('LoginCtrl', function($scope, $http, $location, $ionicPopup, $ionicViewService, $timeout, $ionicLoading, ApiService) {
  var userStr = window.localStorage['userInfo'] || null;
  $scope.loginData = {};
  if(userStr !== null){

    $ionicViewService.nextViewOptions({
      disableBack: true
    });

    $location.path( "/app/home" ); //Start app
  }
  else
    $scope.userData = null;


  // Perform the login action when the user submits the login form
  $scope.doLogin = function() {

    ApiService.login($scope.loginData.username, $scope.loginData.password);

    $ionicLoading.show({template: 'אנא המתן...'}); //close the popup after 3 seconds for some reason
    $timeout(function() {
      $ionicLoading.hide();
      if( (window.localStorage['userInfo'] || false) != false){
        window.localStorage['password'] = $scope.loginData.password;
        var alertPopup = $ionicPopup.alert({
                title: 'ברוכים הבאים!',
                template: 'ההתחברות בוצעה בהצלחה!'
                });
        alertPopup.then(function(res) {
           $ionicViewService.nextViewOptions({
            disableBack: true
            });

          $location.path( "/app/home" ); //Start app 
        });
      }
    }, 2000);

    


};

})

/*=======================================
=            home Controller            =
=======================================*/


.controller('homeCtrl', function($scope, $stateParams, $ionicViewService, $location, $timeout, $rootScope, $ionicModal, ApiService) {


  $scope.lock = {};

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/Aouth.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  $scope.update = function(){
    console.log("[JCE] [info]: Refreshing...");
    ApiService.update();
    if(window.localStorage['newNotes'] === "true")
      $scope.newNotes = true;
    else
      $scope.newNotes = false;

    if(window.localStorage['newGrades'] === "true")
      $scope.newGrades = true;
    else
      $scope.newGrades = false;

    $timeout(function() {
     $scope.$broadcast('scroll.refreshComplete'); //close the popup after 3 seconds for some reason
   }, 3000);

    
  };

  

  $scope.update();

  $scope.goToNotes = function(){
    window.localStorage['newNotes'] = "false";
    $scope.newNotes = false;
    $ionicViewService.nextViewOptions({
      disableBack: true
    });
    $location.path( "/app/jcenews" );
  };

  $scope.goToGrades = function(){
    var localSettingsStr = window.localStorage['Settings'] || null;
    if (localSettingsStr !== null){
      var isLocked = (JSON.parse(localSettingsStr))[0].val;
    }
    if(isLocked){
      console.log("[JCE] [INFO]: Grades Locked");
      $scope.modal.show();
    }
    else{
      window.localStorage['newGrades'] = "false";
      $scope.newGrades = false;
      console.log("Unlocked");
      $ionicViewService.nextViewOptions({
      disableBack: true });
      $location.path( "/app/grades" );
    }
  };

  $scope.isLoggedIn = function(){
    if($scope.userData == null)
      return false;
    console.log("[JCE] [Info] User hase loged in once!");
    return true;
  };

  $scope.$watch('isLoggedIn', function() {
       //
     });


  if(window.localStorage['newNotes'] == "true"){
    $scope.newNotes = true;
  }else{
    $scope.newNotes = false;
  }

  var userStr = window.localStorage['userInfo'] || null;
  if(userStr !== null)
    $scope.userData = JSON.parse(userStr);
  else
    $scope.userData = null;

  

  // Triggered in the Aouth modal to close it
  $scope.closeAouth = function() {
    $scope.modal.hide();
  };

  // Aouth for Grades
  $scope.Aouth = function() {
    console.log("Clicked GoOn - password enterd: "+ $scope.lock.password + "\nThe logs pass is: "+window.localStorage['password']);

    if($scope.lock.password === (window.localStorage['password'] || null)){ //ok
      $scope.lock.password = "";
      $scope.modal.hide();
      window.localStorage['newGrades'] = "false";
      $scope.newGrades = false;
      $ionicViewService.nextViewOptions({
      disableBack: true });

      $location.path( "/app/grades" );
    }else{
      var alertPopup = $ionicPopup.alert({
                title: 'סיסמה שגוייה',
                template: 'טעות בסיסמה'
                });
        alertPopup.then(function(res) {
            $scope.modal.hide();
            });
    }
  };
//////////////////////////////////////////////////////////
  $scope.version = "0.1.28alpha-develop_perview";
/////////////////////////////////////////////////////////
  
});


