angular
        .module('carfriend')
        .controller('ChatsCtrl', ChatsCtrl);

function ChatsCtrl(ChatService, AuthService, $scope, $q, $state, UsersService) {
    console.log("ChatsCTRL loaded");
    var vm = this;

    vm.allChats = [];
    vm.newMessages = []
    vm.currentUser = AuthService.getUser();
    vm.getAllChat = getAllChat;
    vm.removeChat = removeChat;
    vm.goToChat = goToChat;
    vm.doRefresh = doRefresh;

    getAllChat();

 
   $scope.$on("$ionicView.enter", function (scopes, states) {
         $scope.$emit('vynulujChatBadger');
    });
     $scope.$on("$ionicView.leave", function (scopes, states) {
         console.log("ionicView.leave");
         angular.forEach(vm.allChats, function (v, k) {
            if (v.newMessage === true) {
                v['newMessage'] = false;
            }
        })
        var element = angular.element(document.querySelector('#listOfChats'));
        setTimeout(function () {
            $scope.$apply(function () {
                element;
            });
        }, 200);
    });
 
 
    $scope.$on('newMessage', function (event, mass) {
        console.log("newMessage");
        vm.newMessage = true;
        angular.forEach(vm.allChats, function (v, k) {
            if (parseInt(v.id) === parseInt(mass[1].Value)) {
                v['newMessage'] = true;
            }
        })
        var element = angular.element(document.querySelector('#listOfChats'));
        setTimeout(function () {
            $scope.$apply(function () {
                element;
            });
        }, 200);


    });
    ////////////////

    function getAllChat() {
        vm.loadingAllChats = true;
        var users = [];
        var chats = {};
        ChatService.getAll().then(function (chaty) {
            if (chaty.data && chaty.data.data && chaty.data.data.length > 0) {
                chats = chaty.data.data;
                angular.forEach(chats, function (value, key) {
                    if (parseInt(value.user1) !== vm.currentUser.details.id) {
                        users.push(UsersService.fetch(value.user1));
                    }
                    if (parseInt(value.user2) !== vm.currentUser.details.id) {
                        users.push(UsersService.fetch(value.user2));
                    }
                });
                $q.all(users).then(function (u) {
                    users = [];
                    angular.forEach(u, function (value, key) {
                        users.push(value.data);
                    });
                    var final = [];
                    angular.forEach(chats, function (ch) {
                        angular.forEach(users, function (u) {
                            if (u.id === parseInt(ch.user1) || u.id === parseInt(ch.user2)) {
                                delete ch.user1;
                                delete ch.user2;
                                ch.userid = u.id;
                                ch.email = u.email;
                                ch.userType = u.userType;
                                if (u.userType === "driver") {
                                    ch.username = u.cars[0].evidenceNumber;
                                    ch.photoCar = u.cars[0].photo || 'img/car.png';
                                } else {
                                    ch.username = u.username;
                                    ch.photoUser = u.photo || 'img/juzr.png';
                                }
                                final.push(ch);
                            }
                        });
                    });
                    vm.loadingAllChats = false;
                    vm.allChats = final;
                })
            } else {
                vm.loadingAllChats = false;
                vm.allChats = [];
            }
        });
    }
    ;

    ;
    
    function doRefresh(){
        var currentChatsLength = vm.allChats.length; 
        ChatService.getAll().then(function (chaty) {
            if (chaty.data && chaty.data.data && chaty.data.data.length !== currentChatsLength)
                getAllChat();
             $scope.$broadcast('scroll.refreshComplete');                
         });
    };

    function removeChat(chatId) {
        ChatService.removeChat(chatId).then(function (res) {
            angular.forEach(vm.allChats, function (ch, k) {
                if (ch.id === chatId)
                    vm.allChats.splice(k, 1);
            })
        });
    }
    ;
    
    function goToChat(chatId, data){
      console.log("going to chat detail with id: ", chatId);
      return $state.go('tab.chat-detail', {chatId: chatId, user: data});
    }

}

