(function () {
    global.dashModule.factory('$exceptionHandler', ['$log', '$injector', errorHandlerFactory]);

    function errorHandlerFactory($log, $injector) {
        let lastErrorMessage = '';

        return myErrorHandler;

        function myErrorHandler(exception, cause) {
            if (lastErrorMessage !== exception.message) {
                let $http = $injector.get('$http');
                let $ = $injector.get('$');
                let $rootScope = $injector.get('$rootScope');
                let $compile = $injector.get('$compile');
                const params = $.param({
                    message: exception.message,
                    stack: exception.stack
                });

                lastErrorMessage = exception.message;

                $http({
                    method: 'POST',
                    url: 'utils/api/saveJSError',
                    data: params
                }).then(errorLoged, errorLoged);

                const parent = $(document.body);
                const directiveHtml = '<error-dialog></error-dialog>';
                const scope = $rootScope.$new();
                const comp = $compile($(directiveHtml))(scope);
                parent.append(comp);

                $log.error(exception, cause);
                if (window.OnClientError) {
                    window.OnClientError(exception);
                }
            }
        }

        function errorLoged(response) {
            if (response && response.data) {
                $log.warn(response.data);
            }
        }
    }
})();
