(function() {
    'use strict';

    angular
        .module('noodleApp')
        .directive('chatArea', ChatArea);

    ChatArea.$inject = [];
    ChatController.$inject = ['$timeout', 'chatService'];
    function ChatArea() {
        // Usage:
        //      self contained chat widget : <chat-area></chat-area>
        // Creates:
        //
        var directive = {
            bindToController: true,
            controller: ChatController,
            controllerAs: 'vm',
            link: link,
            restrict: 'E',
            replace: false,
            templateUrl: 'app/chat/chat-area.template.html',
            scope:{}
        };
        return directive;

        function link(scope, elm, attrs) {
            element = elm;
        }
    }

    var element;

    /* @ngInject */
    function ChatController ($timeout, chatService) {
        var vm = this;
        vm.messages = [];
        vm.msg = "";
        vm.participants = [];

        var scrollTimeout;

        chatService.notify(function(message){
            vm.messages.push({time: Date.now(), content:message.username + ' connected'});
        },function(message){
            vm.messages.push({time: Date.now(), content:message.username + ' disconnected'});
        },function(message){
            vm.messages.push(message);
            //scroll to bottom
            clearTimeout(scrollTimeout);
            scrollTimeout = setTimeout( function(){
                var chatList = $('.chat-message-list');
                chatList.animate({ scrollTop: chatList[0].scrollHeight}, 250);
            },5);
        }, function(_){ //conversation loaded
            while(vm.messages.length > 0){
                vm.messages.splice(0,1);
            }
        });

        vm.send = function(){
            if(vm.msg.length === 0)
                return;

            var message = {
                time:null,
                user:null,
                content:vm.msg
            };

            chatService.sendMessage(message);

            vm.msg = "";
        };
    }
})();
