/**
 * Created by jaskokoyn on 4/28/2015.
 */
var owlChatEmbedApp  =   angular.module( "owlChatEmbedApp", ['ngSanitize',  'luegg.directives', 'ngCookies']);

owlChatEmbedApp.filter('rawHtml', ['$sce', function($sce){
    return function(val) {
        return $sce.trustAsHtml(val);
    };
}]);

owlChatEmbedApp.controller("chatController", ["$scope", "$http", "$interval","$rootScope", "$timeout", "$cookies", function($scope, $http, $interval, $rootScope, $timeout, $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;
    $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.isCheckingMessages   =   false;
    $scope.fonts                =   fonts;

    $http({
        url: "actions/chat/start-chat.php",
        method: "POST",
        data: {
            cid: cid
        }
    }).success(function(data, status, headers, config) {
        $scope.chatSettings     =   data.settings;
        $scope.canDelete        =   data.canDelete;

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

            return null;
        }

        $scope.messages         =   data.messages;

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

            if($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: 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:    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.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: cid,
                    mid: message.id
                }
            });
        }
    };
}]);