/**
 * Created by jaskokoyn on 2/17/2015.
 */
owlChatApp.controller("chatController", [
    "$scope", "$stateParams", "$http", "$interval","$rootScope", "$timeout", "$state", "$cookies",
    function($scope, $stateParams, $http, $interval, $rootScope, $timeout, $state, $cookies){
        $scope.chatSettings         =   {};
        $scope.messageOpts          =   {
            fontFamily: "Noto Sans",
            fontSize:  12,
            color: "#333",
            bold: false,
            italic: false,
            message: ""
        };
        $scope.messages             =   [];
        $scope.last_mid             =   0;
        $scope.showRoom             =   true;
        $rootScope.last_cid         =   $stateParams.cid;
        $scope.emotes               =   emotes;
        $scope.sendingMessage       =   false;
        $scope.intervalPromise      =   null;
        $cookies.playSound          =   $cookies.playSound ? false : $cookies.playSound;
        $scope.playSound            =   $cookies.playSound;
        $scope.canDelete            =   false;
        $scope.usersOnline          =   [];
        $scope.pmUsers              =   [];
        $scope.isCheckingMessages   =   false;

        $http({
            url: "actions/chat/start-chat.php",
            method: "POST",
            data: $stateParams
        }).success(function(data, status, headers, config) {
            if(data.status == 1){
                $state.go("home");
            }

            $scope.chatSettings     =   data.settings;
            $scope.canDelete        =   data.canDelete;

            if($scope.chatSettings.password !== ""){
                var inputPassword   =   prompt("Please enter password.");

                if(inputPassword !== $scope.chatSettings.password){
                    $state.go("home");
                }
            }

            $scope.messages         =   data.messages;

            $timeout(function(){
                $("#chat_bodyCtr").animate({ scrollTop: $('#chat_bodyCtr')[0].scrollHeight}, 1000);

                if($rootScope.settings.color_btn == 2 || $scope.chatSettings.color_enabled == 2){
                    return null;
                }

                $("#ct_fontColor").spectrum({
                    color: $scope.messageOpts.color,
                    change: function(color){
                        $scope.$apply(function(){
                            $scope.messageOpts.color    =   color.toHexString();
                        });
                    }
                });
            }, 1000);

            $scope.last_mid         =   data.mid.id;

            $scope.intervalPromise  =   $interval(function(){
                $scope.getMessages();
            }, 1000);

            angular.forEach(data.usersOnline, function(value, key){
                $scope.usersOnline.push(value);
            });
        });

        $scope.checkKeyCode         =   function(evt, isValid){
            if(evt.keyCode == 13 && isValid && !$scope.sendingMessage && !evt.shiftKey){
                $scope.submitChatMessage(isValid);
            }
        };

        $scope.submitChatMessage    =   function(isValid){
            if(!isValid){
                return;
            }
            $scope.sendingMessage       =   true;

            $http({
                url: "actions/chat/send-message.php",
                method: "POST",
                data: {
                    opts: $scope.messageOpts,
                    cid: $stateParams.cid
                }
            }).success(function(data, status, headers, config) {
                if(data.status === 1){
                    toastr.warning("Unable to send message. Please wait a bit before sending again.", "Warning!");
                }

                $scope.messageOpts.message  =   "";
                $scope.sendingMessage       =   false;
                $timeout(function(){
                    $(".ct_textarea").focus();
                }, 100);
            });
        };

        $scope.getMessages          =   function(){
            if($scope.isCheckingMessages){
                return null;
            }
            
            $scope.isCheckingMessages   =   true;

            $http({
                url: "actions/chat/get-messages.php",
                method: "POST",
                data: {
                    mid:    $scope.last_mid,
                    cid:    $stateParams.cid
                }
            }).success(function(data, status, headers, config) {
                $scope.isCheckingMessages   =   false;

                if(data.status === 2){
                    $scope.last_mid     =   data.mid.id;
                    if($scope.playSound){
                        alertSound.play();
                    }
                }
                data.messages.forEach(function(ele,ind,arr){
                    $scope.messages.push(ele);
                });
                $scope.pmUsers          =   [];
                data.pms.forEach(function(ele,ind,arr){
                    $scope.pmUsers.push(ele);
                });

                if($scope.messages.length > 50){
                    var messagesCount   =   data.messages.length;
                    for(var i = 0; i < messagesCount; i++){
                        $scope.messages.shift();
                    }
                }
            });
        };

        $scope.showPrivateMessages  =   function(){
            $(".chatPrivateMessageUsersCtr").slideToggle('fast');
        };

        $scope.$on('$destroy',function(){
            if($scope.intervalPromise)
                $interval.cancel($scope.intervalPromise);
        });

        $scope.toggleSound          =   function(){
            $cookies.playSound      =   !$cookies.playSound;
            $scope.playSound        =   !$scope.playSound;
        };

        $scope.removeChatMsg        =   function(message, $index){
            if(confirm("Are you sure you want remove this message? This action can not be undone.")){
                $scope.messages.splice($index, 1);

                $http({
                    method: 'POST',
                    url: 'actions/chat/remove-message.php',
                    data:  {
                        cid: $stateParams.cid,
                        mid: message.id
                    }
                });
            }
        };

        $scope.pmUser               =   function(username){
            $state.go("private_message",{
                username: username
            });
        };
}]);