var notify_location = (window.location.pathname).substring((window.location.pathname).lastIndexOf('/') + 1) == 'chat.html' || (window.location.pathname).substring((window.location.pathname).lastIndexOf('/') + 1) == 'index.html';
//var notify_location = (window.location.pathname).substring((window.location.pathname).lastIndexOf('/') + 1) == 'index.html';
var socket_notify = null;
try {
    socket_notify = io(server_chat);
} catch (err) {
    //window.location.reload();
}
$(window).on('beforeunload', function() {
    socket_notify.close();
});
angular.module('notifiesCtrl', ['LoginService']).controller('notifiesController', function($location, $ionicPlatform, $timeout, $scope, $rootScope, $http, $window, $interval, $cordovaBadge, $cordovaLocalNotification, $cordovaToast, Login, Rooms, Users, Sounds, Chatsettings, Userchatstatuses, $sce, $compile) {
    $scope.currentuser = {};
    $scope.chatarea = {};
    $scope.chatinfo = {};
    $scope.chatinfo.name = ":)";
    $scope.currentsetting = {};
    $scope.message = "";
    $scope.applicationtype = aplicationtype;
    var mousestopTime = "";
    var mousestopoffline = "";
    $scope.histories = [];
    $scope.displayNotify = 0;
    //typing
    $scope.typestatustus = {};
    $scope.typestatustus.prev = "...";
    $scope.typestatustus.disp = "...";
    $scope.typestatustus.current = "...";
    $scope.connected = false;
    $scope.deleteLineitemsData = {};
    $scope.addLineitemsData = {};
    $scope.editRoomsData = {};
    $scope.editRoomsData.selectusers = [];
    //title blink
    $scope.titlemessage = {};
    $scope.titlemessage.disp = "";
    $scope.titlemessage.org = "Chat";
    $scope.titlemessage.current = "";
    $scope.stopblink = {};
    $scope.role = role;
    $scope.dispathroom2 = '';
    $scope.newmessage = 0;
    $scope.load_notify = true;
    $scope.getChatSetting = function() {
        Users.getChatSetting(1).success(function(data) {
            $scope.settingusers = data.settings;
            $scope.currentuser = {
                id: data.id,
                name: data.first_name + ' ' + data.last_name,
                image: pathToPublic + data.image_pic
            };
            $scope.getallNotify(); // lay tat ca cac notify chua close.
            _.each(data.users, function(item) {
                item.status = false;
                item.gethistories = false;
                item.selected = false;
                return item;
            });
            data.users = _.sortBy(data.users, 'time').reverse();
            $scope.users = data.users;
            _.each(data.rooms, function(item) {
                item.gethistories = false;
                item.selected = false;
                return item;
            });
            _.each(data.createrooms, function(item) {
                item.gethistories = false;
                item.selected = false;
                return item;
            });
            data.rooms = arrayUnion(data.rooms, data.createrooms, function(item1, item2) {
                return item1.id == item2.id;
            });
            data.rooms = _.sortBy(data.rooms, 'time').reverse();
            $scope.rooms = data.rooms;
            $scope.sounds = data.sounds;
            $scope.chatstatuses = data.chatstatuses;
            if (data.status) {
                if (data.status.id == "2") {
                    $scope.status = data.status;
                    $scope.notifyStatus(2);
                } else {
                    $scope.status = data.chatstatuses[0];
                    $scope.notifyStatus($scope.status.id);
                }
                setUsername()
            } else {
                if (data.status) {
                    $scope.status = data.chatstatuses[0];
                } else {
                    $scope.status = [];
                }
                $scope.notifyStatus($scope.status.id);
                setUsername()
            };
            var user_id = getParameterByName('user_id');
            $scope.notifyStatus($scope.status.id);
            if (user_id) {
                var is_room = getParameterByName('is_room');
                $scope.getNameChat(user_id, (is_room ? true : false));
            } else {
                if ($scope.rooms.length > 0) {
                    $scope.getNameChat($scope.rooms[0].id, true);
                }
            }
            $('.dashboard > .tblloader').hide();
            $('#document').show();
            request_check_punch_inout = true;
        });
    }
    // $timeout($scope.getChatSetting(),5000);
    $scope.insertEmotico = function(key) {
        $rootScope.$broadcast('insertEmotico', key);
    }
    /*
        close:"1"
        isnotif:"1"
        issound:"1"
        message:"d;"
        name:"TQ"
        room_id:"0"
        sound_i:"3"
        user_id:"70"
        wasplayed:"0"
        from_user:""
        */
    // $scope.getHref = function(item) {
    //     return 'chats.html?user_id=' + (item.room_id == 0 ? item.from_user : item.room_id) + (item.room_id == 0 ? '' : '&is_room=true');
    // }
    $scope.openChat = function(item) {
        var url = 'chat.html#/board/chat/' + (item.room_id == 0 ? item.from_user : item.room_id) + '_' + (item.room_id == 0 ? '' : 'true');
        $scope.closeNotify(item);
        redirectTo(url);
    }
    $scope.openChatTab = function(item) {
        window.open('chats.html?user_id=' + (item.room_id == 0 ? item.from_user : item.room_id) + (item.room_id == 0 ? '' : '&is_room=true'));
        $scope.closeNotify(item);
    }
    $scope.changeStatus = function(item) {
        $scope.status = item;
        $scope.notifyStatus(item.id);
        Userchatstatuses.crudstore({
            user_id: $scope.currentuser.id,
            chatstatus_id: item.id
        }).success(function(data) {
            console.log(data.status);
        });
    }
    $scope.getUserOnline = function() {}
    $scope.getImage = function(user_id) {
        var index = _.findIndex($scope.users, {
            id: user_id + ''
        });
        if (index >= 0) {
            var currUser = $scope.users[index];
            return pathToPublic + currUser.image_pic;
        } else {
            return 'resources/images/thumnails/profile-default.png';
        }
    }
    $scope.getNameChat = function(id, isgroup) {
        // return;
        id = id.toString();
        $scope.unselected();
        if (isgroup == true) {
            var room_index = _.findIndex($scope.rooms, {
                id: id
            });
            $scope.chatinfo = $scope.rooms[room_index];
            $scope.currentsetting = getSettingCurrent(id, isgroup);
            $scope.rooms[room_index].selected = true;
            if (!$scope.rooms[room_index].histories) {
                $scope.rooms[room_index].histories = [];
            }
            if ($scope.rooms[room_index].msg) {
                $scope.rooms[room_index].msg.isread = '1';
                socket_notify.emit('markview', $scope.rooms[room_index].msg);
            }
            if (!$scope.rooms[room_index].gethistories) {
                socket_notify.emit('gethistories', $scope.currentsetting);
            }
            $scope.histories = $scope.rooms[room_index].histories;
        } else {
            var user_index = _.findLastIndex($scope.users, {
                id: id.toString()
            });
            $scope.chatinfo = $scope.users[user_index];
            $scope.currentsetting = getSettingCurrent(id, isgroup);
            $scope.users[user_index].selected = true;
            if ($scope.users[user_index].msg) {
                $scope.users[user_index].msg.isread = '1';
                socket_notify.emit('markview', $scope.users[user_index].msg);
            }
            if (!$scope.users[user_index].histories) {
                $scope.users[user_index].histories = [];
            }
            if (!$scope.users[user_index].gethistories) {
                socket_notify.emit('gethistories', $scope.currentsetting);
            }
            $scope.histories = $scope.users[user_index].histories;
        }
        if ($scope.histories.length == 0) {
            $scope.histories.push({
                'message': ''
            });
        }
        $scope.stopBlink();
    }

    function getSettingCurrent(id, isgroup) {
        if (isgroup == true) {
            var settings = _.where($scope.settingusers, {
                toroom_id: id
            });
            if (settings.length > 0) {
                return settings[0];
            } else {
                return {
                    "fromuser_id": $scope.currentuser.id,
                    "touser_id": 0,
                    "toroom_id": id,
                    "isnotification": settingChat.isnotification,
                    "isnotifybackground": settingChat.isnotifybackground,
                    "issound": settingChat.issound,
                    "sound_id": settingChat.sound_id
                };
            }
        } else {
            var settings = _.where($scope.settingusers, {
                touser_id: id
            });
            if (settings.length > 0) {
                return settings[0];
            } else {
                return {
                    "fromuser_id": $scope.currentuser.id,
                    "touser_id": id,
                    "toroom_id": 0,
                    "isnotification": settingChat.isnotification,
                    "isnotifybackground": settingChat.isnotifybackground,
                    "issound": settingChat.issound,
                    "sound_id": settingChat.sound_id
                };
            }
        }
    }
    $scope.changeSetting = function() {
        if (!updateSettingCurrent()) {
            Chatsettings.save($scope.currentsetting).success(function(data) {
                console.log('save chatsetting');
            });
        } else {
            Chatsettings.update($scope.currentsetting.fromuser_id, $scope.currentsetting).success(function(data) {
                //$scope.histories.push(data);
            });
        }
    }

    function updateSettingCurrent() {
        var curr = $scope.currentsetting;
        var findSetting = _.findLastIndex($scope.settingusers, {
            fromuser_id: curr.fromuser_id,
            touser_id: curr.touser_id,
            toroom_id: curr.toroom_id
        });
        if (findSetting >= 0) {
            $scope.settingusers[findSetting] = curr;
            return true;
        } else {
            $scope.settingusers.push(curr);
            return false;
        }
    }

    function setUsername() {
        var status = ($scope.status.id == 1 || $scope.status.id == '1') ? true : false;
        $scope.currentuser.status = status;
        socket_notify.emit('add user', $scope.currentuser);
        $scope.connected = true;
    }
    var allowHashTag; // Cho phep Hashtag
    $scope.c;
    $scope.searchHashtag = {};
    $scope.searchHashtag.display_name = '';
    $scope.hashtags = [];
    $scope.sendMessage = function($event) {
        var keyCode = $event.which || $event.keyCode;
        var that = $('#message');
        var text = that.val().trim();
        var curr_postion = that.getCursorPosition();
        var beforeC = text.charAt(curr_postion - 2);
        var isOpeningHashTagSuggest = $('#hastagpopup').is(':visible');
        if (!isOpeningHashTagSuggest) {
            if ($scope.c == "#" || $scope.c == "@") {
                if (beforeC == "" || beforeC == " ") {
                    openHashtagSuggest('#message');
                } else {
                    closeHashtagSuggest();
                }
            }
        } else {
            $scope.filterHashtag(text, curr_postion);
            if ($scope.c == " ") {
                closeHashtagSuggest();
            } else if ($event.which == 8) {
                if (beforeC == "" || beforeC == " ") {
                    //closeHashtagSuggest();
                }
            }
        }
        if (keyCode == 13 && text.length > 0) {
            closeHashtagSuggest();
            if (socket_notify.connected) {
                var message = replaceHtml(text);
                message = replaceEmoticon(message);
                message = replaceHashtag(message);
                socket_notify.emit('new message', {
                    from_user: $scope.currentsetting.fromuser_id,
                    room_id: $scope.currentsetting.toroom_id,
                    user_id: $scope.currentsetting.touser_id,
                    contents: message,
                    hashtag: '',
                    applicationtype: aplicationtype.text
                });
                var msg = {
                    id: '',
                    from_user: $scope.currentsetting.fromuser_id,
                    room_id: $scope.currentsetting.toroom_id,
                    user_id: $scope.currentsetting.touser_id,
                    username: $scope.currentuser.name,
                    message: message,
                    time: moment().format('YYYY-MM-DD HH:mm:ss'),
                    applicationtype: aplicationtype.text
                };
                // $scope.msg_time=msg.time;
                $scope.histories.push(msg);
                $scope.message = "";
                $('#message').val('');
                $('#message').selectionStart = 0;
            } else {
                alert('Connect error, please check your connection!');
            }
        } else {
            $scope.currentsetting.from_name = $scope.currentuser.name;
            socket_notify.emit('typing', $scope.currentsetting)
        }
    }
    $scope.hashtag = function(item) {
        closeHashtagSuggest();
        $rootScope.$broadcast('hashtag', item.display_name, $scope.searchHashtag.display_name);
    }
    $scope.notifyForUserTag = function(name) {
        console.log(name);
    }
    $scope.filterHashtag = function(text, curr_postion) {
        var substring = text.substring(0, curr_postion);
        var lastInfdexAt = substring.lastIndexOf('#');
        var lastInfdexhash = substring.lastIndexOf('@');
        if (lastInfdexhash > lastInfdexAt) {
            lastInfdexAt = lastInfdexhash;
        }
        $scope.searchHashtag.display_name = text.substring(lastInfdexAt + 1, curr_postion);
    }
    $scope.checkKeypress = function($event) {
        $scope.c = String.fromCharCode($event.which);
    }

    function openHashtagSuggest(s) {
        $('#hastagpopup').show();
        var pos = $(s).getCaretPosition();
        $('#hastagpopup').css({
            left: pos.left,
            bottom: 75 - pos.top
        });
        console.log(s.offsetLeft);
        // $('#hastagpopup').css({
        //  left: s.offsetLeft + pos.left,
        //  top: s.offsetTop + pos.top + 20
        // });
    }

    function closeHashtagSuggest() {
        $('#hastagpopup').hide();
    }
    /*{ "fromuser_id": $scope.currentuser.id, "touser_id": id, "toroom_id": 0, "isnotification": settingChat.isnotification,
    "isnotifybackground": settingChat.isnotifybackground,
    "issound":  settingChat.issound, "sound_id": settingChat.sound_id};*/
    // {
    //     room_id: 0,
    //     user_id: 0,
    //     name: "",
    //     isnotifybackground: 0,
    //     issound: 0,
    //     sound_id: "",
    //     wasplayed: 1,
    //     message: "",
    //     close: "1"
    // }
    $scope.notifylist = [];
    $scope.playSound = function(index, sound_id) {
        var sound_index = $scope.findIndex($scope.sounds, {
            id: sound_id
        });
        if (sound_index >= 0) {
            var sound = $scope.sounds[sound_index];
            // myAudio = document.getElementById("myAudio");
            try {
                myAudio.src = sound.file_path;
            } catch (e) {}
            try {
                myAudio.play();
            } catch (e) {
                console.log(e)
            }
        }
    }
    $scope.lastScroll = 0;
    $scope.isrequest = true;
    $scope.myScrollEvent = function(e) {
        var top = $('#chat-history').scrollTop();
        // console.log(top);
        if (top <= 5 && $scope.isrequest) {
            $scope.isrequest = false;
            $('#loader').show();
            // console.log($scope.currentsetting);
            $scope.currentsetting.min_id = _.first($scope.histories).id;
            // console.log($scope.currentsetting);
            socket_notify.emit('gethistoriespaging', $scope.currentsetting);
        }
        $scope.lastScroll = top;
    }
    /*
        applicationtype: "text"
        contents: "<img src="emoticon/zing_14.png"/>"
        from_user: "1"
        id:3361
        isread: "0"
        message: "<img src="emoticon/zing_14.png"/>"
        room_id: "0"
        time:"016-02-24 11:01:57"
        user_id: "70"
        username: "TQ"
        */
        $scope.pushNotify = function(obj, message, localPushData, group) {
            if (group) {
                setting = $scope.findSetting({
                    toroom_id: message.room_id + '',
                    touser_id: '0'
                });
            } else {
                setting = $scope.findSetting({
                    toroom_id: message.room_id + '',
                    touser_id: message.from_user
                })
            }
            var last_message = -1;
            var notify_index = -1;
            var room_id = message.room_id + '';
            var from_user = message.from_user + '';
            notify_index = removeIndex(room_id, from_user, last_message);
            var content = '';
            if (message.applicationtype == 'text') {
                content = message.contents || message.message;
            } else {
                content = '[send file] ' + (message.contents || message.message);
            }
            var tag = $scope.findHasTag(message.hashtag);
            var fromuser = _.where($scope.users, {
                id: message.from_user + ''
            });
            var notify = {
                from_user: message.from_user,
                image_pic: obj.image_pic || fromuser[0].image_pic,
                room_id: message.room_id,
                user_id: message.user_id,
                name: obj.name || obj.nick_name,
                isnotification: setting.isnotification,
                issound: setting.issound,
                sound_id: setting.sound_id,
                wasplayed: '0',
                message: content,
                servertime: message.time,
                hashtag: tag,
                counter: message.counter,
                username: message.username,
                close: "1"
            }
            if ($scope.load_notify) {
                $scope.removeNotify(notify_index);
            $scope.load_notify = false; //chay 1 lan
        }
        if (notify_index >= 0) {
            $scope.notifylist[notify_index] = notify;
        }
        if (notify.issound == '1') { //chi push khi duoc setting notify la 1
            $scope.playSound(0, setting.sound_id);
        }
        if ((notify.isnotification == '1' || tag == true) && notify_index < 0) {
            $scope.notifylist.push(notify);
        }
        if (notify.isnotification == '1' && localPushData) {
            var user_index = _.findLastIndex($scope.users, {
                id: localPushData.from_user
            });
            var username = $scope.users[user_index].display_name;
            var prefix = localPushData.room_id == 0 ? username : '[' + localPushData.room_name + ']' + username;
            var content = localPushData.applicationtype == 'image' ? '[image]' : localPushData.message;
            content = prefix + ':' + content;
            $cordovaToast.showLongTop(content);
        }
        if (localPushData) {
            $scope.localPush(localPushData.from_user, localPushData.message, localPushData.room_id, localPushData.applicationtype, localPushData.room_name, localPushData.username);
        }
        $scope.displayNotify = $scope.recounterLength();
        $scope.newmessage = sumNewMessage($scope.notifylist) + $scope.displayNotify;
        // $scope.$emit('pushCounter',$scope.notifylist.length+"/"+($scope.newmessage +  $scope.displayNotify));
    }
    $scope.recounterLength = function() {
        $scope.displayNotify = 0;
        for (var i = $scope.notifylist.length - 1; i >= 0; i--) {
            var item = $scope.notifylist[i];
            if (item.isnotification == 1 || item.hashtag == true) {
                $scope.displayNotify += 1;
            }
        };
        return $scope.displayNotify;
    }

    function sumNewMessage(notifylist) {
        var sum = 0;
        for (var i = notifylist.length - 1; i >= 0; i--) {
            var item = notifylist[i];
            if (item && item.counter) {
                if (item.counter == 0) {
                    sum += 1;
                } else {
                    sum += parseInt(item.counter);
                }
            }
        };
        return sum;
    }
    $scope.localPush = function(fromuser_id, message, room_id, applicationType, room_name, username) {
        var user_index = _.findLastIndex($scope.users, {
            id: fromuser_id
        });
        var username = $scope.users[user_index].display_name;
        var idPush = room_id == 0 ? fromuser_id : (1000 + room_id);
        var user_id = room_id == 0 ? fromuser_id : room_id;
        var is_room = room_id == 0 ? false : true;
        var prefix = room_id == 0 ? username : '[' + room_name + ']' + username;
        var content = applicationType == 'image' ? '[image]' : message;
        content = prefix + ':' + content;
        $cordovaLocalNotification.getAllIds().then(function(ids) {
            if (ids.indexOf(parseFloat(idPush)) == -1) {
                $timeout(function() {
                    $scope.badge++;
                    $cordovaBadge.increase(1);
                }, 3000);
            }
        });
        $cordovaLocalNotification.schedule({
            id: idPush,
            text: content,
            led: "0000FF",
            icon: cordova.file.applicationDirectory + 'www/resources/images/icons/icon.png',
            sound: cordova.file.applicationDirectory + 'www/sounds/tweeters.ogg',
            data: {
                user_id: user_id,
                is_room: is_room
            }
        })
    }

    function removeIndex(room_id, from_user, last_message) {
        for (var i = 0; i < $scope.notifylist.length; i++) {
            if (last_message >= 0) {
                break;
            }
            if ($scope.notifylist[i].room_id != 0) {
                if ($scope.notifylist[i].room_id + '' == room_id) {
                    last_message = i;
                } else {
                    last_message = -1;
                }
            } else {
                if ($scope.notifylist[i].from_user + '' == from_user && $scope.notifylist[i].room_id == room_id) {
                    last_message = i;
                } else {
                    last_message = -1;
                }
            }
        }
        return last_message;
    }
    $scope.findHasTag = function(hastag) {
        if (!hastag) {
            return false;
        } else {
            var tag = '@' + $scope.currentuser.name.replace(/ /g, '_');
            var tag2 = '#' + $scope.currentuser.name.replace(/ /g, '_');
            var hashtags = hastag.split(',');
            return hashtags.indexOf(tag) > -1 ? true : false || (hashtags.indexOf(tag2) > -1 ? true : false);
        }
        return false;
    }
    $scope.findSetting = function(obj) {
        var findSetting = _.findLastIndex($scope.settingusers, obj);
        if (findSetting >= 0) {
            return $scope.settingusers[findSetting];
        } else {
            return settingChat;
        }
    }
    $scope.closeNotify = function(obj) {
        if (obj != 'all') {
            var findSetting = _.findLastIndex($scope.notifylist, obj);
            socket_notify.emit('closenotify', {
                from_user: obj.from_user,
                user_id: obj.user_id,
                room_id: obj.room_id,
                isclose: 1
            });
            $scope.notifylist.splice(findSetting, 1);
            $scope.displayNotify = $scope.recounterLength();
            $scope.newmessage = sumNewMessage($scope.notifylist) + $scope.displayNotify;
        } else {
            for (var i = $scope.notifylist.length - 1; i >= 0; i--) {
                var item = $scope.notifylist[i];
                socket_notify.emit('closenotify', {
                    from_user: item.from_user,
                    user_id: item.user_id,
                    room_id: item.room_id,
                    isclose: 1
                });
                $scope.notifylist.splice(i, 1);
            }
            $scope.notifylist = [];
            $scope.displayNotify = $scope.recounterLength();
            $scope.newmessage = sumNewMessage($scope.notifylist) + $scope.displayNotify;
        }
    }
    $scope.findNotify = function(obj) {
        var findSetting = _.findLastIndex($scope.notifylist, obj);
        return findSetting;
    }
    $scope.removeNotify = function(index) {
        $scope.notifylist.splice(index, 1);
    }
    $scope.findIndex = function(data, obj) {
        return _.findLastIndex(data, obj);
    }
    $scope.findRoomIndex = function(room) {
        return $scope.findIndex($scope.rooms, room);
    }
    $scope.removeRoom = function(room_index) {
        $scope.rooms.splice(room_index, 1);
    }
    $scope.addRoom = function(room, room_index, user_index) {
        room.users = [];
        $scope.rooms.push(room);
    }
    $scope.updateRoom = function(room, room_index) {
        room.users = [];
        $scope.rooms[room_index] = room;
    }
    $scope.shortname = function(history) {
        var index = history.message ? (history.message.lastIndexOf("/") + 1) : (history.contents.lastIndexOf("/") + 1);
        return (history.message ? history.message.substring(index) : history.contents.substring(index));
    }
    $scope.getLineitems = function() {
        $('.loader').show();
    };
    $scope.getNickname = function(item) {
        var user_index = _.findLastIndex($scope.users, {
            id: item
        });
        if (user_index >= 0) {
            return $scope.users[user_index].nick_name;
        } else {
            return "You";
        }
    }
    $scope.$watch('file', function(file) {
        if (!file) {
            $scope.uploadfile($scope.file);
        }
    });
    $scope.uploadfile = function(files) {
        $scope.files = files;
        angular.forEach(files, function(file) {
            if (file != null) {
                console.log(file);
                var data = {
                    from_user: $scope.currentsetting.fromuser_id,
                    room_id: $scope.currentsetting.toroom_id,
                    user_id: $scope.currentsetting.touser_id,
                    hashtag: '',
                    applicationtype: aplicationtype.file
                };
                if (file.type.indexOf('image/') >= 0) {
                    data.applicationtype = aplicationtype.image;
                }
                file.upload = Upload.upload({
                    url: url_server + 'lineitems',
                    data: data,
                    file: file
                });
                file.upload.success(function(data) {
                    console.log(data);
                    $scope.histories.push(data.lineitem);
                    socket_notify.emit('send file', data.lineitem);
                    $scope.progress = -1;
                })
                file.upload.then(function(response) {
                    $timeout(function() {
                        file.result = response.data;
                    });
                }, function(response) {
                    if (response.status > 0) $scope.errorMsg = response.status + ': ' + response.data;
                });
                file.upload.progress(function(evt) {
                    file.upload = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                    $scope.progress = file.upload;
                });
            }
        });
    }
    $scope.getUserLogin = function() {
        return Login.getUserLogin().success(function(data) {
            if (data == false) {
                $scope.displayname = "Profile";
            } else {
                var displayname = (data.first_name != null ? data.first_name : '') + ' ' + (data.last_name == null ? '' : data.last_name);
                if ($.trim(displayname) == "") {
                    $scope.displayname = "Hello, " + data.email;
                } else {
                    $scope.displayname = "Hello, " + displayname;
                }
            }
        });
    }
    //$scope.getUserLogin();
    $scope.logout = function() {
        return Login.logout().success(function(data) {
            $window.location.href = url_login;
        });
    }
    $scope.checkLogin = function() {
        return Login.checkLogin().success(function(data) {
            if (data.status == false) {
                $window.location.href = url_login;
            } else {
                $scope.currentIdLogin = data.status.id;
                $scope.imagePath = pathToPublic + data.status.image_pic;
            }
        });
    }
    // $scope.checkLogin();
    // stopTime = $interval($scope.checkLogin, time_refresh);
    /*Room*/
    $scope.addRoomsData = {};
    $scope.createRooms = function() {
        console.log($scope.addRoomsData);
        Rooms.save($scope.addRoomsData).success(function(data) {
            if (data.status) {
                closePopupById('popupAddGroupChat');
                $scope.rooms.push(data.room);
                socket_notify.emit('create room', data.room);
                $scope.addRoomsData = {};
                toastr.success(data.msg);
            } else {
                toastr.error(data.msg);
            }
        });
    }
    $scope.editRooms = function(id) {
        $('.loader').show();
        Rooms.show(id).success(function(data) {
            $('.loader').hide();
            $scope.editRoomsData = data;
            $scope.editRoomsData.selectusers = data.users;
        });
    }
    $scope.updateRooms = function() {
        var id = $scope.editRoomsData.id;
        $('.loader').show();
        Rooms.update(id, $scope.editRoomsData).success(function(data) {
            $('.loader').hide();
            if (data.status) {
                closePopupById('popupEditGroupChat');
                toastr.success(data.msg);
                $scope.editRoomsData = {};
                var room_index = $scope.findRoomIndex({
                    id: data.room.id
                });
                if (room_index >= 0) {
                    socket_notify.emit('create room', data.room);
                    $scope.updateRoom(data.room, room_index);
                }
            } else {
                toastr.error(data.msg);
            }
        });
    }
    $scope.refreshUserEdit = function(address) {
        if (address.length > 0) {
            var params = {
                search: address
            };
            Users.getSelect2ByChat(params).success(function(data) {
                var diff = differentArray(data, $scope.editRoomsData.selectusers);
                $scope.searchusers = diff;
            })
        } else {
            $scope.searchusers = [];
        }
    };
    $scope.addRoomsData.selectusers = [];
    $scope.refreshAddresses = function(address) {
        if (address.length > 0) {
            var params = {
                search: address
            };
            Users.getSelect2ByChat(params).success(function(data) {
                var diff = differentArray(data, $scope.addRoomsData.selectusers);
                $scope.searchusers = diff;
            })
        } else {
            $scope.searchusers = [];
        }
    };
    /*End Room*/
    /*START SOCKET_notify*/
    socket_notify.on('gethistoriespaging', function(data) {
        $('#loader').hide();
        $rootScope.$apply(function() {
            $scope.isrequest = true;
            if (data.histories.length == 0) return;
            data.histories = data.histories.reverse();
            if (data.current.toroom_id != 0) {
                var room_index = _.findIndex($scope.rooms, {
                    id: data.current.toroom_id
                });
                $scope.rooms[room_index].histories = data.histories.concat($scope.rooms[room_index].histories);
                if ($scope.currentsetting.toroom_id == data.current.toroom_id) {
                    $scope.histories = $scope.rooms[room_index].histories;
                }
            } else {
                var user_index = _.findLastIndex($scope.users, {
                    id: data.current.touser_id
                });
                $scope.users[user_index].histories = data.histories.concat($scope.users[user_index].histories);
                if ($scope.currentsetting.touser_id == data.current.touser_id) {
                    $scope.histories = $scope.users[user_index].histories;
                }
            }
        });
    })
    /*
    id: 2486
    from_user:"1"
    room_id:"1"
    user_id:"1"
    username:"TQ"
    message:"fsdfsdf]"
    time:"2016-01-26 14:29:00"
    applicationtype:"text"
    */
    socket_notify.on('new message', function(data) {
        // console.log('not');
        // console.log($scope.currentsetting);
        // console.log($scope.currentsetting.fromuser_id + '===>' + data.user_id + '>>>' + $scope.currentsetting.toroom_id + '===>' + data.room_id);
        var localPushData = {};
        localPushData.from_user = data.from_user;
        localPushData.message = data.message;
        localPushData.room_id = data.room_id;
        localPushData.applicationtype = data.applicationtype;
        localPushData.username = data.username;
        localPushData.room_name = '';
        if (data.room_id != 0) { //group
            // console.log(data);
            if ($scope.currentsetting.toroom_id == data.room_id) {
                $rootScope.$apply(function() {
                    $scope.stopBlink();
                    $scope.blink(data.username, data.message);
                    $scope.histories.push(data);
                });
            } else {
                $rootScope.$apply(function() {
                    var room_index = _.findLastIndex($scope.rooms, {
                        id: data.room_id
                    });
                    if (room_index >= 0) { // neu room ton tai thi dua vao
                        if (!$scope.rooms[room_index].histories) {
                            $scope.rooms[room_index].histories = [];
                        }
                        $scope.rooms[room_index].histories.push(data);
                        if ($scope.currentsetting.toroom_id != data.room_id) {
                            $scope.rooms[room_index].msg = data;
                            $scope.rooms[room_index].msg.contents = data.message;
                            $scope.rooms[room_index].msg.isread = '0';
                            localPushData.room_name = $scope.rooms[room_index].name;
                            $scope.pushNotify($scope.rooms[room_index], data, localPushData, true);
                        }
                    }
                });
            }
        } else {
            if ($scope.currentsetting.touser_id == data.from_user) { //neu thuc su gui cho hien tai
                var user_index = _.findLastIndex($scope.users, {
                    id: data.from_user
                });
                var currentuser = $scope.users[user_index];
                $rootScope.$apply(function() {
                    $scope.stopBlink();
                    $scope.blink(data.username, data.message);
                    $scope.histories.push(data);
                    // $scope.pushNotify($scope.rooms[room_index], data, localPushData, true);
                    $scope.pushNotify(currentuser, data, localPushData, false);
                });
            } else {
                $timeout(function() {
                    if ($scope.currentuser.id == data.user_id) {
                        var user_index = _.findLastIndex($scope.users, {
                            id: data.from_user
                        });
                        if (user_index >= 0) { // neu user ton tai thi dua vao
                            if (!$scope.users[user_index].histories) {
                                $scope.users[user_index].histories = [];
                            }
                            $scope.users[user_index].histories.push(data);
                            $scope.users[user_index].msg = data;
                            $scope.users[user_index].msg.contents = data.message;
                            $scope.users[user_index].msg.isread = '0';
                            localPushData.room_name = $scope.users[user_index].name;
                            $scope.pushNotify($scope.users[user_index], data, localPushData, false);
                        }
                    }
                }, 10);
            }
        }
    });
    socket_notify.on('create room', function(data) {
        var room = {
            id: data.id
        };
        var user = {
            id: $scope.currentuser.id
        };
        var room_index = $scope.findRoomIndex(room);
        var user_index = _.findLastIndex(data.users, user);
        console.log(data);
        console.log(room_index + '=======>' + user_index);
        $rootScope.$apply(function() {
            //khi user khong so huu phong
            if (room.user_id != $scope.currentuser.id) {
                if (room_index >= 0 && user_index < 0) {
                    $scope.removeRoom(room_index);
                }
                if (room_index >= 0 && user_index >= 0) {
                    $scope.updateRoom(data, room_index);
                }
                if (room_index < 0 && user_index >= 0) {
                    $scope.addRoom(data, room_index, user_index);
                }
            } else {
                if (room_index >= 0 && user_index >= 0) {
                    $scope.updateRoom(data, room_index);
                }
                if (room_index < 0 && user_index >= 0) {
                    $scope.addRoom(data, room_index, user_index);
                }
            }
        });
    });
    $scope.stopTyping = {};
    socket_notify.on('reconnect', function() {
        setUsername();
    });
    /*
    fromuser_id "70"
    isnotification "1"
    isnotifybackground "1"
    issound "1"
    sound_id"1"
    toroom_id 0
    touser_id "3655"
    */
    socket_notify.on('gethistories', function(data) {
        $timeout(function() {
            if (data.current.toroom_id != 0) {
                var room_index = _.findIndex($scope.rooms, {
                    id: data.current.toroom_id
                });
                if (!$scope.rooms[room_index].histories) {
                    $scope.rooms[room_index].histories = [];
                }
                $scope.rooms[room_index].histories = data.histories.reverse();
                $scope.rooms[room_index].gethistories == true;
                if ($scope.currentsetting.toroom_id == data.current.toroom_id) {
                    $scope.histories = data.histories;
                }
            } else {
                var user_index = _.findLastIndex($scope.users, {
                    id: data.current.touser_id
                });
                if (!$scope.users[user_index].histories) {
                    $scope.users[user_index].histories = [];
                }
                $scope.users[user_index].histories = data.histories.reverse();
                $scope.users[user_index].gethistories == true;
                if ($scope.currentsetting.touser_id == data.current.touser_id) {
                    $scope.histories = data.histories;
                }
            }
        }, 0);
    })
    socket_notify.on('changestatus', function(data) {
        $timeout(function() {
            var user = {
                id: data.user_id
            };
            if (!data.v) {
                return;
            }
            if (user.id == $scope.currentuser.id) {
                var status = _.find($scope.chatstatuses, {
                    id: data.status + ''
                });
                if (status) {
                    $scope.status = status;
                    $scope.notifyStatusNoEmit($scope.status.id);
                }
                return;
            }
            var index = $scope.findIndex($scope.users, user);
            if (index >= 0) {
                if (data.status == 3) { //offline;
                    $scope.users[index].status = false;
                    $scope.users[index].idle = false;
                    $scope.users[index].disturb = false;
                } else { //1 online, 2 ndisturb, 4 idle;
                    $scope.users[index].status = true;
                    $scope.users[index].idle = (data.status == 4) ? true : false;
                    $scope.users[index].disturb = (data.status == 2) ? true : false;
                }
            }
        }, 10);
    });
    socket_notify.on('list online', function(data) {
        $timeout(function() {
            for (var p in data) {
                _.each($scope.users, function(item) {
                    if (item.id == p) {
                        item.status = data[p];
                    }
                    return item;
                });
            }
        }, 0);
    })
    socket_notify.on('getallnotifies', function(data) {
        if (data.notifies != null) {
            $timeout(function() {
                for (var i = 0; i < data.notifies.length; i++) {
                    var message = data.notifies[i];
                    var obj = {};
                    if (message.room_id > 0) {
                        obj = _.findWhere($scope.rooms, {
                            id: message.room_id + ''
                        });
                    } else {
                        obj = _.findWhere($scope.users, {
                            id: message.from_user + ''
                        });
                    }
                    if (obj) {
                        $scope.pushNotify(obj, message, null, (message.room_id > 0 ? true : false));
                    }
                }
            }, 0);
        }
    })
    socket_notify.on("logoutsignal",function(data){
        if(data.user_id==$scope.currentuser.id){
            localStorage.setItem("login_status", "0");
            localStorage.setItem("email", "");
            localStorage.setItem("token", "");
            $ionicLoading.hide();
            redirectTo('index.html');
        }
    });
    /*END SOCKET_notify*/
    /*Message converter*/
    function replaceEmoticon(msg) {
        for (key in $scope.emoticon) {
            var test = key.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
            var re = new RegExp(test, 'g');
            msg = msg.replace(re, '<img src="' + $scope.emoticon[key] + '"/>');
        }
        return msg;
    }

    function replaceHtml(msg) {
        return msg.replace(/(http|ftp|https:\/\/[\w\-_]+\.{1}[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/gi, '<a class="link" href="$1$2" target="_blank">$1$2</a>');
    }

    function replaceHashtag(msg) {
        msg = msg.replace(/([\#@][a-zA-Z0-9\-\_]+)/g, "<span class='hash-tag'>$1</span>");
        return msg;
    }
    /*End Message converter*/
    /*typing*/
    $scope.typingmessage = function() {
        $scope.typestatustus.current = '...';
    }
    $scope.blink = function(name, message) {
        $scope.titlemessage.disp = name + " say " + message;
        if (message.applicationtype == 'images') {
            $scope.titlemessage.disp = name + " send image.";
        }
        if (message.applicationtype == 'file') {
            $scope.titlemessage.disp = name + " send file."
        }
        $scope.stopblink = $interval($scope.blinkTitle, 1500);
    }
    $scope.blinkTitle = function() {
        if ($scope.titlemessage.current == $scope.titlemessage.org) {
            $scope.titlemessage.current = $scope.titlemessage.disp;
        } else {
            $scope.titlemessage.current = $scope.titlemessage.org;
        }
    }
    $scope.stopBlink = function() {
        $scope.titlemessage.current = "";
        $interval.cancel($scope.stopblink);
    }
    $scope.formatTime = function(datetime) {
        var dd_datetime = moment(datetime).format('YYYY-MM-DD');
        var today = moment().format('YYYY-MM-DD');
        if (dd_datetime == today) {
            return moment(datetime).format('h:mm A');
        } else {
            return moment(datetime).format('YYYY-MM-DD  h:mm A');
        }
    }
    /*end typing*/
    /*Event mouse*/
    // chatstatuses
    $scope.flag_disturb = false;
    $scope.threadhold = true;
    $scope.blur = function() {
        if ($scope.threadhold && $scope.connected) {
            $scope.threadhold = false;
            $timeout(function() {
                if ($scope.status) {
                    if ($scope.status.id == 2) { //non disturb
                        $interval.cancel(mousestopTime);
                        $interval.cancel(mousestopoffline);
                        if (!$scope.flag_disturb) {
                            $scope.notifyStatus(2);
                            $scope.flag_disturb = true;
                        }
                        $scope.threadhold = true;
                        return;
                    }
                    $scope.flag_disturb = false;
                    if ($scope.status.id == 4 || $scope.status.id == 3) {
                        $scope.status = _.find($scope.chatstatuses, function(item) {
                            return item.id == 1;
                        });
                        $scope.threadhold = true;
                        $scope.notifyStatus(1);
                        return;
                    }
                    if ($scope.status.id == 1) {
                        $interval.cancel(mousestopoffline);
                        $interval.cancel(mousestopTime);
                        mousestopoffline = undefined;
                        mousestopTime = undefined;
                        mousestopTime = $interval($scope.setIdle, time_idle);
                    }
                    $scope.threadhold = true;
                }
            }, 250);
        }
    }
    $scope.setIdle = function() {
        $scope.status = _.find($scope.chatstatuses, function(item) {
            return item.id == 4;
        });
        $interval.cancel(mousestopoffline);
        $interval.cancel(mousestopTime);
        $scope.notifyStatus(4);
    }
    $scope.setOffline = function() {
        $scope.status = _.find($scope.chatstatuses, function(item) {
            return item.id == 3;
        });
        $interval.cancel(mousestopoffline);
        $interval.cancel(mousestopTime);
        $scope.notifyStatus(3);
    }
    $scope.notifyStatusNoEmit = function(id) {
        switch (id) {
            case '1':
            case 1:
            $interval.cancel(mousestopoffline);
            $interval.cancel(mousestopTime);
            mousestopoffline = undefined;
            mousestopTime = undefined;
            mousestopTime = $interval($scope.setIdle, time_idle);
            break;
            case '2':
            case 2:
            $interval.cancel(mousestopTime);
            $interval.cancel(mousestopoffline);
            break;
            case '3':
            case 3:
            $interval.cancel(mousestopoffline);
            mousestopoffline = undefined;
            $interval.cancel(mousestopTime);
            mousestopTime = undefined;
            break;
            case '4':
            case 4:
                //thong bao idle
                $interval.cancel(mousestopTime);
                mousestopTime = false;
                mousestopoffline = $interval($scope.setOffline, time_offline);
                break;
            }
        }
        $scope.notifyStatus = function(id) {
            switch (id) {
                case '1':
                case 1:
                $interval.cancel(mousestopoffline);
                $interval.cancel(mousestopTime);
                mousestopoffline = undefined;
                mousestopTime = undefined;
                mousestopTime = $interval($scope.setIdle, time_idle);
                socket_notify.emit('changestatus', {
                    user_id: $scope.currentuser.id,
                    status: 1,
                    v: 1
                })
                break;
                case '2':
                case 2:
                $interval.cancel(mousestopTime);
                $interval.cancel(mousestopoffline);
                socket_notify.emit('changestatus', {
                    user_id: $scope.currentuser.id,
                    status: 2,
                    v: 1
                });
                break;
                case '3':
                case 3:
                $interval.cancel(mousestopoffline);
                mousestopoffline = undefined;
                $interval.cancel(mousestopTime);
                mousestopTime = undefined;
                socket_notify.emit('changestatus', {
                    user_id: $scope.currentuser.id,
                    status: 3,
                    v: 1
                });
                break;
                case '4':
                case 4:
                //thong bao idle
                socket_notify.emit('changestatus', {
                    user_id: $scope.currentuser.id,
                    status: 4,
                    v: 1
                });
                $interval.cancel(mousestopTime);
                mousestopTime = false;
                mousestopoffline = $interval($scope.setOffline, time_offline);
                break;
            }
        }
        $scope.unselected = function() {
            _.each($scope.users, function(item) {
                item.selected = false;
                return item;
            });
            _.each($scope.rooms, function(item) {
                item.selected = false;
                return item;
            });
        }
        /*end typing*/
        $scope.getallNotify = function() {
            socket_notify.emit('getallnotifies', {
                user_id: $scope.currentuser.id
            });
        }
        $scope.trustAsHtml = function(data) {
            if (data) {
                return $sce.trustAsHtml(data);
            }
        }
        $scope.formatDate = function(item, style) {
            if (style == 'timestamp') {
                if (item.time < 0) return;
                return moment(item.time * 1000).format("DD MMM YYYY hh:mm a");
            }
            if (item && item.time) {
                return moment(item.time).format("DD MMM YYYY hh:mm a");
            } else {
                return "test";
            }
        }
        $ionicPlatform.registerBackButtonAction(function(event) {
            closeTarget('#popupNotify');
        }, 100);
        $scope.getChatSetting();
        $scope.limitLoaded = false;
        $scope.$on('$includeContentLoaded', function(e) {
            if (!notify_location) {
                var myVarChat = setInterval(function() {
                    myTimerChat()
                }, 100);

                function myTimerChat() {
                    if (!$scope.limitLoaded) {
                        $scope.limitLoaded = true;
                        $scope.getChatSetting();
                        request_notify_get_chat = false;
                        clearInterval(myVarChat);
                    }
                }
            }
        });
    })