'use strict';

// Session module. Provide session factory $sessionFactory
angular
    .module('session', ['ngCookies'])
    // I think I dont need this controller
    .controller('UserCtrl', ["$rootScope", "session", "$location", "userConfig", "PushNotification", "$scope", "notifyCode",
            "AppUtil", "APIName", "util", "Events", "ClientInfo", "$", '$filter', '$sce', '_', "logo", "app", "$state",
            function ($rootScope, session, $location, userConfig, PushNotification, $scope, notifyCode, AppUtil, APIName,
                      util, Events, ClientInfo, $, $filter, $sce, _, logo, app, $state) {
                $scope.innitTheme = false;
                $scope.$on('$viewContentLoaded', function () {
                    if (!$scope.innitTheme) {
                        theme.init();
                        $scope.innitTheme = true;
                    }
                });
                // We get user information
                $rootScope.user = session.getUser();
                $rootScope.logo = logo;
                // current language
                $rootScope.currentLanguage = session.getCurrentLanguage();
                // Update name of user
                if ($rootScope.currentLanguage === 'ja' || $rootScope.currentLanguage === 'vi') {
                    $rootScope.userName = $rootScope.user.last_name + " " + $rootScope.user.first_name;
                } else {
                    $rootScope.userName = $rootScope.user.first_name + " " + (($rootScope.user.middle_name) ? $rootScope.user.middle_name : "") + " " + $rootScope.user.last_name;
                }

                // Define Code filter for notification event
                $rootScope.codes = Events.PROJECT.USER_INVITED.code + "," + Events.PROJECT.USER_CREATE_COMMENT.code + "," + Events.PROJECT.FILE_ADDED.code + "," + Events.PROJECT.USER_UPDATE_COMMENT.code;

                var origin = $rootScope.user;
                $rootScope.isShowNumberOfNotify = false;
                $rootScope.countNumberNotification = 0;

                $rootScope.listMessage = [];
                $rootScope.isEventLoading = false;
                //$rootScope.loadWaiting = false;
                $rootScope.endLoading = false;
                $rootScope.sever_time = null;
                // Track total record response from service
                $rootScope.remaining_record = null;

                // Check Trial Account
                $rootScope.isTrialUser = false;

                function checkTrialAccount() {
                    var userInfo = session.getUser();
//                var paramsGetTeam = {auth_token: userInfo, team_id: userInfo.team_id};
                    if (userInfo.role_id !== userConfig.SUPER_ADMIN.role && userInfo.role_id !== userConfig.COMPANY_ADMIN.role) {
                        AppUtil.createRequest({
                            name: APIName.GET_TEAM.name + userInfo.team_id,
                            method: "GET"
                        }, {}, function (data) {

                            // expiry trial days inform
                            var currentDate = new Date();
                            var createDate = new Date(data.data.create_date);

                            $rootScope.expiryTrialDays = 0;
                            $rootScope.days = currentDate.getTime() - createDate.getTime();
                            $rootScope.days = Math.round($rootScope.days / 1000 / 60 / 60 / 24);

                            if ($rootScope.days <= 30)
                                $rootScope.expiryTrialDays = 30 - $rootScope.days;

                            var status = data.data.status;
                            if (status === 6 && data.data.email_address === userInfo.mail_address)
                                $rootScope.isTrialUser = true;
                        });
                    }
                }

                $rootScope.$on('account-payment-change', function (event, data) {
                    if (data === 'active')
                        $rootScope.isTrialUser = false;
                });

                var defaultPageSize = 5;
                // current page size request
                var pageSize = null;

                var nav = navigator;

                var email;

                function checkExist(array, value) {
                    var result = $.inArray(value, array);

                    return result !== -1;
                }

                // Do logout
                $rootScope.doLogout = function () {
                    $rootScope.isTrialUser = false;
                    session.logout(function (user) {

                        switch (user.role_id) {

                            case userConfig.SUPER_ADMIN.role:

                                $state.go("adminLogin");
                                break;

                            case userConfig.COMPANY_ADMIN.role:
                                $state.go("adminLogin");
                                break;

                            default:
                                if (app.ON_PREMISE) {
                                    $state.go("loginLdap");
                                } else {
                                    $state.go("adminLogin");
                                }

                                break;
                        }
                        // just support to store the data in one session
                        localStorage.clear();
                    });
                };

                // Callback function for Socket Notification
                $rootScope.notify = function (message) {
                    switch (message.code) {
                        case notifyCode.ADD_COMMENT.code:
                            if (message.projectId === $rootScope.project_id && message.body.comment.userId !== $rootScope.user.user_id) {
                                $rootScope.notifyNewStatus();
                            }
                            if ($rootScope.project_id === null || typeof $rootScope.project_id === 'undefined') {
                                $rootScope.checkUnreadMessage();
                            }
                            // Notify for user in other project
                            else if (message.notifyUserIds && checkExist(message.notifyUserIds, $rootScope.user.user_id)) {
                                $rootScope.notifyNewStatus();
                            }
                            //reset list message when having new notify to push new message to the top
                            $rootScope.listMessage = [];
                            break;
                        case notifyCode.ADD_FILE.code:
                            if (message.projectId === $rootScope.project_id && message.body.userId !== $rootScope.user.user_id) {
                                $rootScope.notifyNewStatus();
                            }
                            if ($rootScope.project_id === null || typeof $rootScope.project_id === 'undefined') {
                                $rootScope.checkUnreadMessage();
                            }
                            // Notify for user in other project
                            else if (message.notifyUserIds && checkExist(message.notifyUserIds, $rootScope.user.user_id)) {
                                $rootScope.notifyNewStatus();
                            }
                            //reset list message when having new notify to push new message to the top
                            $rootScope.listMessage = [];
                            break;
                        case notifyCode.ADD_FILE_CLOUD.code:
                            if (message.projectId === $rootScope.project_id && message.body.userId !== $rootScope.user.user_id) {
                                $rootScope.notifyNewStatus();
                            }
                            if ($rootScope.project_id === null || typeof $rootScope.project_id === 'undefined') {
                                $rootScope.checkUnreadMessage();
                            }
                            //reset list message when having new notify to push new message to the top
                            $rootScope.listMessage = [];
                            break;
                        case notifyCode.INVITE_USER.code:
                            if (message.body.userId === $rootScope.user.user_id) {
                                $rootScope.notifyNewStatus();
                            }
                            // Notify for user in other project
                            else if (message.notifyUserIds && checkExist(message.notifyUserIds, $rootScope.user.user_id)) {
                                $rootScope.notifyNewStatus();
                            }
                            //reset list message when having new notify to push new message to the top
                            $rootScope.listMessage = [];
                            break;
                        case notifyCode.COPY_PROJECT.code:

                            // $rootScope.$broadcast("copied_project_notify", message);

                            //reset list message when having new notify to push new message to the top
                            $rootScope.listMessage = [];
                            break;
                    }
                };

                // author: @Nhan Huynh
                // catch the new notification
                $scope.$on("new_notify", newNotification);

                function newNotification(event, value) {
                    $rootScope.notify(value);
                }

                $rootScope.notifyNewStatus = function () {
                    $rootScope.countNumberNotification++;
                    if (ClientInfo.getBrowser({nagivator: nav}) === 'IE') {
                        $(".notify-number").css({'display': 'block', 'margin-left': '5px'});
                        $(".notify-number").removeClass('ng-hide');
                        $scope.$apply();
                    } else {
                        $rootScope.isShowNumberOfNotify = true;
                        $scope.$apply();
                    }

                };

                // register broasdcast messange notify when project change
                $rootScope.$on('currentProjectId', function (event, data) {
                    $rootScope.project_id = data.projectId;
                    var option = {
                        team_id: $rootScope.user.team_id,
                        project_id: $rootScope.project_id,
                        token: session.getToken()
                    };
                    PushNotification.initializeSocketSystemNotification($rootScope.notify, option);

                });

                $rootScope.loadNotification = function () {

                    var option = {
                        team_id: $rootScope.user.team_id,
                        project_id: null,
                        token: session.getToken()
                    };
                    PushNotification.initializeSocketSystemNotification($rootScope.notify, option);
                };

                $scope.isShowMailBox = true;

                function init() {
                    if ($rootScope.user.role_id === userConfig.SUPER_ADMIN.role || $rootScope.user.role_id === userConfig.COMPANY_ADMIN.role) {
                        $scope.isShowMailBox = false;
                    }

                    // Update name of user
                    if (session.getCurrentLanguage() === 'ja') {
                        $rootScope.userName = $rootScope.user.last_name + " " + $rootScope.user.first_name;
                    } else {
                        $rootScope.userName = $rootScope.user.first_name + " " + (($rootScope.user.middle_name) ? $rootScope.user.middle_name : "") + " " + $rootScope.user.last_name;
                    }

                    $rootScope.isShowHistoryMenu = true;
                    $rootScope.isShowAddressBookMenu = true;
                    $rootScope.isShowUserMenu = true;
                    $rootScope.isShowReport = true;

                    // Check user role
                    if ($rootScope.user.role_id !== userConfig.ADMIN.role
                        && $rootScope.user.role_id !== userConfig.COMPANY_ADMIN.role
                        && $rootScope.user.role_id !== userConfig.SUPER_ADMIN.role
                        && $rootScope.user.role_id !== userConfig.MANAGER.role
                        && $rootScope.user.role_id !== userConfig.MEMBER.role
                    ) {
                        $rootScope.isShowHistoryMenu = false;
                        $rootScope.isShowAddressBookMenu = false;
                        $rootScope.isShowUserMenu = false;
                    }

                    if ($rootScope.user.role_id !== userConfig.ADMIN.role
                        && $rootScope.user.role_id !== userConfig.MANAGER.role
                        && $rootScope.user.role_id !== userConfig.MEMBER.role
                    ) {
                        $rootScope.isShowReport = false;
                    }

                    /// checkTrialAccount();
                    checkTrialAccount();
                }

                $rootScope.goUsers = function () {
                    localStorage.tabs = 1;
                    $state.go("userList");
                };
                $rootScope.goAddress = function () {
                    localStorage.tabs = 1;
                    $state.go("addressBookList");
                };
                $rootScope.goUsagePackages = function () {
                    localStorage.tabs = 1;
                    $state.go("usagePackage");
                };

                $rootScope.checkUnreadMessage = function () {
                    // var params = {
                    //     team_id: $rootScope.user.team_id,
                    //     codes: $rootScope.codes,
                    //     last_update: (new Date().getTime())
                    // };
                    // AppUtil.createRequest(APIName.GET_MESSAGE_BOX_UNREAD, params, function (res) {
                    //     $rootScope.countNumberNotification = res.data.total_elements;
                    //     if ($rootScope.countNumberNotification > 0) {
                    //         if (ClientInfo.getBrowser({nagivator: nav}) === 'IE') {
                    //             $(".notify-number").css({'display': 'block', 'margin-left': '5px'});
                    //             $(".notify-number").removeClass('ng-hide');
                    //         } else {
                    //             $rootScope.isShowNumberOfNotify = true;
                    //         }
                    //     }
                    // });
                };

                // End callback Socket notification
                $rootScope.loadMessage = function (scroll) {

                    //stop execute method when there is no inbox message more;
                    if (($rootScope.remaining_record === null || $rootScope.remaining_record >= 0) && $rootScope.isEventLoading === false) {
                        $rootScope.isEventLoading = true;
                        var numberOfNotify = $rootScope.countNumberNotification;
                        $rootScope.countNumberNotification = 0;
                        if (ClientInfo.getBrowser({nagivator: nav}) === 'IE') {
                            $(".notify-number").css({'display': 'none', 'margin-left': '5px'});
                            $(".notify-number").removeClass('ng-hide');
                        } else {
                            $rootScope.isShowNumberOfNotify = false;
                        }

                        var length = $rootScope.listMessage.length;

                        var lastDate = (length > 0 && scroll) ? ($rootScope.listMessage[length - 1].last_update || 0) : 0;
                        if (numberOfNotify > defaultPageSize) {
                            pageSize = numberOfNotify;
                            //$rootScope.loadWaiting = true;
                        } else {
                            pageSize = defaultPageSize;
                        }
                        //call API
                        var params = {
                            page_size: pageSize,
                            codes: $rootScope.codes,
                            last_update: lastDate
                        };

                        var objUrl = {
                            method: APIName.GET_MESSAGE_BOX.method,
                            name: APIName.GET_MESSAGE_BOX.name + $rootScope.user.team_id
                        };
                        AppUtil.createRequest(objUrl, params, function (res) {
                            //$rootScope.loadWaiting = false;
                            if (scroll) { // scroll
                                $rootScope.listMessage = $rootScope.listMessage.concat(res.data.content);
                            } else { // load for the first time
                                $rootScope.listMessage = res.data.content;
                            }
                            $rootScope.sever_time = new Date().getTime();
                            $rootScope.isEventLoading = false;
                            $rootScope.remaining_record = res.data.total_elements;
                        });
                    }
                };

                // Load more event
                $scope.$on("$loadMoreEvents", function () {
                    $rootScope.loadMessage(true);
                });


                $rootScope.getText = function (message) {
                    var result = "";
                    var userName = "";
                    if (session.getCurrentLanguage() === 'ja')
                        userName = message.from_user_last_name + " " + message.from_user_first_name;
                    else
                        userName = message.from_user_first_name + " " + message.from_user_last_name;
                    result += userName;
                    switch (message.code) {
                        case Events.PROJECT.USER_INVITED.code:
                            result += util.translate("message_text.invite_project");
                            break;
                        case Events.PROJECT.USER_CREATE_COMMENT.code:
                            if (message.message_text && isMention(message.message_text)) {
                                result += util.translate("message_text.mention");
                            } else {
                                if (message.file_id) {
                                    result += util.translate("message_text.file_comment");
                                } else {
                                    result += util.translate("message_text.comment");
                                }
                            }
                            break;
                        case Events.PROJECT.USER_UPDATE_COMMENT.code:
                            if (message.message_text && isMention(message.message_text)) {
                                result += util.translate("message_text.mention");
                            } else {
                                if (message.file_id) {
                                    result += util.translate("message_text.update_file_comment");
                                } else {
                                    result += util.translate("message_text.update_comment");
                                }
                            }
                            break;
                        case Events.PROJECT.FILE_ADDED.code:
                            result += util.translate("message_text.upload_file");
                            break;
                    }

                    return result;
                };

                $rootScope.getMessageTime = function (message) {
                    return millisecondsToStr($rootScope.sever_time - message.last_update) + util.translate("message_text.ago");
                };

                $rootScope.getContent = function (message) {
                    var result;
                    switch (message.code) {
                        case Events.PROJECT.USER_INVITED.code:
                            result = message.project_name;
                            break;
                        case Events.PROJECT.USER_CREATE_COMMENT.code:
                            if (message.file_id) {
                                result = message.file_name;
                            } else {
                                result = message.project_name;
                            }
                            break;
                        case Events.PROJECT.USER_UPDATE_COMMENT.code:
                            if (message.file_id) {
                                result = message.file_name;
                            } else {
                                result = message.project_name;
                            }
                            break;
                        case Events.PROJECT.FILE_ADDED.code:
                            result = message.file_name + util.translate("message_text.on") + message.project_name;
                            break;

                    }
                    return result;
                };

                $rootScope.redrawChartToggle = function () {
                    $rootScope.$broadcast('redraw-chart-toggle');
                };

                //check if comment has mention to this user
                function isMention(message) {
                    var text = $sce.getTrustedHtml($filter('escape_text')(message, true));
                    //try to get email
                    email = $rootScope.user ? $rootScope.user.mail_address : null;

                    if (!email) {
                        return false;
                    }

                    var isTag = false;
                    //get mention tag from pattern @[email]
                    var mentions = text.match(/@\[(.*?)]/gi);

                    if (!mentions) {
                        return false;
                    }
                    //find mention tags point to current user
                    for (var i = 0; i < mentions.length; i++) {
                        if (mentions[i] === '@[' + email + ']') {
                            isTag = true;
                            break;
                        }
                    }
                    if (isTag) {
                        return true;
                    }
                    return false;

                }

                function numberEnding(number) {
                    return (number > 1) ? util.translate("time.s") : '';
                }

                function millisecondsToStr(milliseconds) {

                    var temp = Math.floor(milliseconds / 1000);
                    var years = Math.floor(temp / 31536000);
                    if (years) {
                        return years + util.translate("time.year") + numberEnding(years);
                    }
                    //TODO: Months! Maybe weeks?
                    var days = Math.floor((temp %= 31536000) / 86400);
                    if (days) {
                        return days + util.translate("time.day") + numberEnding(days);
                    }
                    var hours = Math.floor((temp %= 86400) / 3600);
                    if (hours) {
                        return hours + util.translate("time.hour") + numberEnding(hours);
                    }
                    var minutes = Math.floor((temp %= 3600) / 60);
                    if (minutes) {
                        return minutes + util.translate("time.minute") + numberEnding(minutes);
                    }
                    var seconds = temp % 60;
                    if (seconds) {
                        return seconds + util.translate("time.second") + numberEnding(seconds);
                    }
                    return util.translate("time.now"); //'just now' //or other string you like;
                }

                // innit
                init();
            }]
    );
