app.controller('SelectMenuPageController',['$scope','$firebaseObject','$timeout','$interval','$window',function($scope,$firebaseObject,$timeout,$interval,$window){
  if(firebase.auth().currentUser){
    $scope.ref = firebase.database().ref().child('users').child(firebase.auth().currentUser.uid).child('meals');
  } else{
    $scope.ref = firebase.database().ref().child('meals');
  }
  $interval(function(){
    if(firebase.auth().currentUser){
      $scope.ref = firebase.database().ref().child('users').child(firebase.auth().currentUser.uid).child('meals');
    } else{
      $scope.ref = firebase.database().ref().child('meals');
    }

    $scope.ref.on('value', snap => {
      $timeout(function(){
        $scope.meals = snap.val();
      })
    })
  },1000)
  // var ref = firebase.database().ref().child('meals');

  $scope.mealType = 'breakfast';
  $scope.meals = [];
  $scope.selectedNumber = 0;

  $scope.selectMeal = function(i){
    if(firebase.auth().currentUser){
      var keys = Object.keys($scope.meals);
      //animating btn
      if(!$scope.meals[keys[i]].isSelected){
        var selectedMealsBtn = angular.element(document.querySelector('.selected-meals-btn'));
        selectedMealsBtn.addClass('selected-meals-btn-animate');
        $timeout(function(){
          selectedMealsBtn.removeClass('selected-meals-btn-animate');
        },500)
      }
      //animating btn
      $scope.meals[keys[i]].isSelected = true;
      $scope.ref.child(keys[i]).set($scope.meals[keys[i]]);
    } else{
      var loginPopupJQ = angular.element(document.querySelector('.login-popup'));
      loginPopupJQ.css('display','flex');
      $timeout(function(){
        loginPopupJQ.css('opacity','1');
      },50)
    }
  }

  $scope.ref.on('value', snap => {
    $timeout(function(){
      $scope.meals = snap.val();
    })
  })

  var firebaseMainMeals = firebase.database().ref().child('meals');
  var firebaseUsers = firebase.database().ref().child('users');
  firebaseUsers.on('value', function(snap){
    $scope.testUsers = snap.val();

  })
  firebaseMainMeals.on('value',function(snap){
    $scope.mainObjDelete = snap.val();

  })

  $scope.deleteMealItem = function(key){
    var userKeys = Object.keys($scope.testUsers);
    for (let i = 0; i < userKeys.length; i++) {
      // var user = users[usersKeys[i]];
      var newObject = $scope.testUsers[userKeys[i]].meals;
      var userMealsKeys = Object.keys($scope.testUsers[userKeys[i]].meals);
      delete newObject[userMealsKeys[key]]
      firebaseUsers.child(userKeys[i]).child('meals').set(Object.assign(newObject));
    }


    var mainObjKeys = Object.keys($scope.mainObjDelete);
    delete $scope.mainObjDelete[mainObjKeys[key]];
    firebaseMainMeals.set(Object.assign($scope.mainObjDelete));
    // $timeout(function(){
    //   $window.location.reload();
    // },1000)
  }

}])
