app.controller('UserPageController',['$scope','$http',function($scope,$http){
  //navigation btns
  $scope.activeBtn = 'personal info';
  //navigation btns

  var ref = firebase.database().ref().child('users').child(firebase.auth().currentUser.uid).child('userObject');
  var ref2 = firebase.database().ref().child('users').child(firebase.auth().currentUser.uid).child('userDiets');
  ref.on('value',function(snap){
    $scope.userObject = snap.val();
    if($scope.userObject){
      $scope.newUserObject = Object.assign($scope.userObject);
    }
  })

  ref2.on('value',function(snap){
    $scope.userDiets = snap.val()
  })

  $scope.isShowInputs = false;
  $scope.toggleIsShowInputs = function(){
    if($scope.isShowInputs){
      ref.set($scope.newUserObject);
      $scope.isShowInputs = !$scope.isShowInputs;
    } else{
      $scope.isShowInputs = !$scope.isShowInputs;
    }
  }

  //AIzaSyCHfQNLTRwK9C24adja3xs79GtqeKOTIOE - google apies

  $http.get('https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json').then(function(response){
    $scope.countriesObject = response.data;
  })

  // chat
  $scope.messageObject = {
    userMessage: ''
  };

  $scope.sendMessage = function(){
    if($scope.messageObject.userMessage){
      $scope.messageObject.uid = firebase.auth().currentUser.uid;
      var date = new Date();
      // $scope.messageObject.name = $scope.userObject.name || 'user';
      // $scope.messageObject.surname = $scope.userObject.surname || '';
      $scope.messageObject.date = date.getHours() + ':' + (date.getMinutes().toString().length < 2?'0'+date.getMinutes():date.getMinutes())
      firebase.database().ref().child('users').child(firebase.auth().currentUser.uid).child('chat').push().set($scope.messageObject);
      $scope.messageObject.userMessage = '';
    }
  }

  var chatRef = firebase.database().ref().child('users').child(firebase.auth().currentUser.uid).child('chat');
  chatRef.on('value', function(snap){
    $scope.messages = snap.val();
  })
  // chat

  // change image
  $scope.storage = firebase.storage().ref();
  firebase.storage().ref(firebase.auth().currentUser.uid).getDownloadURL().then(function(url){
    $scope.userAvatarUrl = url;
  })
  $scope.changeImg = function(e){
    var file = e.target.files[0];
    var fileName = firebase.auth().currentUser.uid;
    var metadata = {
      contentType: file.type
    };
    var task = $scope.storage.child(fileName).put(file, metadata);
    task.then(function(snapshot){
      $scope.userAvatarUrl = snapshot.downloadURL;
    }).catch(function(error){
      console.log(error);
    })
  }
  // change image
}])
