/**
 * Created by jaskokoyn on 2/18/2015.
 */
owlChatApp.controller("pmController", [
    "$scope", "$stateParams", "$http", "$interval", "$rootScope", "$state", "$timeout",
    function($scope, $stateParams, $http, $interval, $rootScope, $state, $timeout){
        $scope.username             =   $stateParams.username;
        $rootScope.pmUsername       =   $scope.username;
        $scope.messageOpts          =   {
            fontFamily: "Noto Sans",
            fontSize:  12,
            color: "#333",
            bold: false,
            italic: false,
            message: ""
        };
        $scope.emotes               =   emotes;
        $scope.messages             =   [];
        $scope.last_mid             =   0;
        $scope.last_cid             =   $rootScope.last_cid;
        $scope.sendingMessage       =   false;
        $scope.intervalPromise      =   null;
        $scope.pmUsers              =   [];
        $scope.isCheckingMessages   =   false;

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

            $("#ct_fontColor").spectrum({
                color: $scope.messageOpts.color,
                change: function(color){
                    $scope.messageOpts.color    =   color.toHexString();
                }
            });
            $scope.messages         =   data.messages;
            $scope.last_mid         =   data.mid.id;
            $scope.pmUsers          =   data.pmUsers;
            $scope.settings         =   $rootScope.settings;

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

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

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

            $http({
                url: "actions/pm/send-pm.php",
                method: "POST",
                data: {
                    opts: $scope.messageOpts,
                    username: $stateParams.username
                }
            }).success(function(data, status, headers, config) {
                // this callback will be called asynchronously
                // when the response is available
                console.log(data);
                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.checkKeyCode         =   function(evt, isValid){
            if(evt.keyCode == 13 && isValid && !$scope.sendingMessage && !evt.shiftKey){
                $scope.submitChatMessage(isValid);
            }
        };

        $scope.$on('$destroy',function(){
            $rootScope.pmUsername   =   null;

            if($scope.intervalPromise)
                $interval.cancel($scope.intervalPromise);
        });

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

            $scope.isCheckingMessages   =   true;

            $http({
                url: "actions/pm/get-pms.php",
                method: "POST",
                data: {
                    mid:            $scope.last_mid,
                    username:       $stateParams.username
                }
            }).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');
        };
}]);