app.controller('MessagesPageController',['$scope','$timeout',function($scope,$timeout){

  // gettig of user images url
  $scope.userImages = {};
  var firebaseUsers = firebase.database().ref().child('users');
  firebaseUsers.on('value',function(snap){
    $scope.users = snap.val();
    $scope.userKeys = Object.keys($scope.users)
    for (let i = 0; i < $scope.userKeys.length; i++) {
      firebase.storage().ref($scope.userKeys[i]).getDownloadURL().then(function(url){
        $scope.userImages[$scope.userKeys[i]] = url;

      }).catch(function(error){
        console.log(error);
      })
    }
    $scope.selectedUser = $scope.userKeys[0];
  })
  // gettig of user images url

  // chat output
  $scope.selectUser = function(key){
    $scope.selectedUser = key;
  }
  // chat output

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

  $scope.sendMessage = function(){
    var selectedUser = $scope.selectedUser;
    if($scope.messageObject.userMessage){
      $scope.messageObject.uid = 'uRkqD9GmNxUsdgF1XtmPicDJwAz1';
      var date = new Date();
      // $scope.messageObject.name = 'Admin';
      // $scope.messageObject.surname = '';
      $scope.messageObject.date = date.getHours() + ':' + (date.getMinutes().toString().length < 2?'0'+date.getMinutes():date.getMinutes())
      firebase.database().ref().child('users').child($scope.selectedUser).child('chat').push().set($scope.messageObject);
      $scope.messageObject.userMessage = '';
      $scope.selectedUser = selectedUser;
    }
    console.log($scope.userKeys.indexOf($scope.selectedUser))
  }

  //send message

}])
