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

function NewChatCtrl($state, ionicMaterialInk, ChatService, AuthService, CarService, $q, $scope) {
    var vm = this;

    vm.currentUser = AuthService.getUser();
    vm.newChat = newChat;
    vm.creatingNewChat = false;
    
    ionicMaterialInk.displayEffect();
    
    ////////////

    function newChat(data, backToChat) {   
        vm.creatingNewChat = true;
        var chatInfo = {};
        var toChats= {};
        if(backToChat && backToChat.backToChat)
            toChats.chats = true;
        var promises = [];
        if (data.evidenceNumber) {
            chatInfo.otherUser = data.user;
            chatInfo.photo = data.photo || 'img/car.png';
            chatInfo.username = data.evidenceNumber;
            promises.push(CarService.getUserByCarId(data.id));
        } else {
            chatInfo.otherUser = data.id;
            chatInfo.photo = data.photo || 'img/juzr.png';
            chatInfo.username = data.username;
            chatInfo.email = data.email;
        }
        /* hladanie ci chat uz nahodou neexistuje. na serveri sa kontroluje pomocou preddefinovanych filtrov*/
        promises.push(ChatService.findOne(vm.currentUser.details.id, chatInfo.otherUser));
        promises.push(ChatService.findOne(chatInfo.otherUser, vm.currentUser.details.id));
 
        var chatId;

        $q.all(promises).then(function (chat) {
            if(chat.length === 3){
                chatInfo.email = chat[0];
                chat.splice(0, 1);
            }
            angular.forEach(chat, function (obj) {
                if (obj.data.totalRows !== 0)
                    chatId = obj.data.data[0].id;
            });

            if (chatId) {
                vm.creatingNewChat = false;
                $scope.$emit('clearChatsField');
                return goToChat(chatId, chatInfo, toChats);
            } else {
                var nChat = {
                    user1: vm.currentUser.details.id,
                    user2: chatInfo.otherUser
                };

                ChatService.createChat(nChat).then(function (success) {
                    vm.creatingNewChat = false;
                    $scope.$emit('clearChatsField');
                    return goToChat(success.data.__metadata.id, chatInfo, toChats);
                }, function (err) {
                    console.log(err);
                    // return handleError(err);
                });
            }
        });
    };

    function goToChat(chatId, data, toChats) {
        console.log("gottochat", chatId, data, toChats)
      return $state.go('tab.chat-detail', {chatId: chatId, user:data, from: toChats});
    }
}