(function () {
    global.dashModule
        .controller('activityCheckerCtrl', ['$scope', '$timeout', '$window', '$http', 'utilsService', activityCheckerCtrl])
        .directive('activityChecker', [activityCheckerDirective]);

    function activityCheckerDirective() {
        return {
            restrict: 'E',
            templateUrl: 'utils/html/activityCheckerTemplate'
        };
    }

    function activityCheckerCtrl($scope, $timeout, $window, $http, utilsService) {
        $scope.checkLastActivity = checkLastActivity;
        $scope.activityDialogClose = activityDialogClose;
        $scope.hasTimeExpired = false;

        const MAX_INACTIVE_TIME = 1000 * 60 * 24;

        function checkLastActivity() {
            $timeout(checkActivityOnServer, MAX_INACTIVE_TIME);
        }

        function checkActivityOnServer(){
            $http({
                method: 'POST',
                url: 'utils/api/checkActivityStatus'
            }).then(showInactiveMessage, utilsService.onHttpError);
        }

        function showInactiveMessage(response) {
            if(response.data && response.data.hasSessionExpired === true){
                $scope.hasTimeExpired = true;
            }else{
                checkLastActivity();
            }
        }

        function activityDialogClose(){
            $window.location.href = 'logout.php';
        }
    }
})();
