'use strict';

var reports = angular.module('reports', [
        'ui.sortable',
        'ngSanitize',
        'ngRoute',
        'reportServiceModule',
        'inventoryServiceModule',
        'autocompleteServiceModule',
        'commonDirectives',
        'commonHelperModule',
        'commonFiltersModule',
        'env.environmentServiceModule',
        'rulesServiceModule',
        'dc.naviTreeService',
        'fileChangesSqlService',
        'fimService',
        'ngCookies',
        'ui.bootstrap',
        'inventoryDirectives',
        'inclExclDirectives',
        'notificationServiceModule',
        'inclExcl.naviTreeService',
        'includeExcludeServiceModule',
        'autoCompleteServiceModule',
        'inclExcl.paginationServiceModule',
        'inventoryHelpers',
        'changesDirectives',
        'daterangepicker',
        'inventoryDataServiceModule',
        'inventoryFilterServiceModule',
        'healthDiagnosticsServiceModule',
        'hubManagementServiceModule',
        'highChartsDirective',
        'addConditionDirective',
        'dashboardApp.filters',
        'autocompleteInputDirective',
        'healthIssueDirective',
        'breadcrumbsDirective',
        'customFilter',
        'selectFileDirective',
        'complianceWidgetHelper',
        'complianceHelperModule',
        'editableFieldModule',
        'tableDirectiveModule',
        'groupsDirective',
        'saveFilterAsGroupDirective',
        'personalGroupsServiceModule',
        'sharedGroupsServiceModule'
    ],
   function($routeProvider, $locationProvider) {
            $locationProvider.hashPrefix('');

            //reports created or subscribed by user
            $routeProvider.when('/', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/listreports',
                controller: indexController
            });



            // all available reports (only reports allowed by permissins) without own reports
            $routeProvider.when('/allreports', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/allreports',
                controller: allreportsController
            });


            /*
             * Run report without param, this means that SQL string saved inside scope
             */
            $routeProvider.when('/report/run', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/reportresults',
                controller: resultController
            });

            /*
             * Run specific report
             */
            $routeProvider.when('/report/run/:reportid/', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/reportresults',
                controller: resultController
            });

            $routeProvider.when('/report/external', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/reportresults',
                controller: resultController
            });

            $routeProvider.when('/report/external/sql/:sql/', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/reportresults',
                controller: resultController
            });

            /*
             *  Open empty SQLWIZARD page
             */
            $routeProvider.when('/custom/new', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/editreport',
                controller: editController
            });

            // when we run new report and then we want to edit it
            $routeProvider.when('/custom/edit', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/editreport',
                controller: editController
            });
            /*
             * Edit report  by id
             */
            $routeProvider.when('/custom/edit/:reportid/', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/editreport',
                controller: editController
            });


            $routeProvider.when('/report/schedule', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/schedulereport',
                controller: scheduleController
            });

            $routeProvider.when('/report/schedule/:reportid/', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/schedulereport',
                controller: scheduleController
            });


            $routeProvider.when('/inventory', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/inventory',
                controller: inventoryController
            });

            $routeProvider.when('/changes', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/changes',
                controller: changesController
            });

            $routeProvider.when('/file_integrity_monitoring', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/fim',
                controller: fileIntegrityMonitoringController
            });

            $routeProvider.when('/changes/run/:reportid', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/changes',
                controller: changesController
            });
            $routeProvider.when('/inventory/run/:reportid', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/inventory',
                controller: inventoryController
            });

            $routeProvider.when('/inventory/alert/:alertid', {
                templateUrl: MP_SITE_URL + '/advancedreports/partials/inventory',
                controller: inventoryController
            });

            /*
             * Health Diagnostic reports routes
             */
            $routeProvider.when('/health-diagnostic/unreachable-hosts', {
                templateUrl: MP_SITE_URL + '/advancedreports/hostDiagnosticView/notRecentlyCollected',
                controller: healthDiagnosticController
            });

            $routeProvider.when('/health-diagnostic/policy-errors', {
                templateUrl: MP_SITE_URL + '/advancedreports/hostDiagnosticView/lastAgentRunUnsuccessful',
                controller: healthDiagnosticController
            });

            $routeProvider.when('/health-diagnostic/duplicate-ids', {
                templateUrl: MP_SITE_URL + '/advancedreports/hostDiagnosticView/hostsUsingSameIdentity',
                controller: healthDiagnosticController
            });

           $routeProvider.when('/health-diagnostic/missing-reporting-data', {
                templateUrl: MP_SITE_URL + '/advancedreports/hostDiagnosticView/hostsNeverCollected',
                controller: healthDiagnosticController
            });

           $routeProvider.when('/health-diagnostic/deleted-hosts-report', {
               templateUrl: MP_SITE_URL + '/advancedreports/hostDiagnosticView/deletedHostsReport',
               controller: healthDiagnosticController
           });

           $routeProvider.when('/health-diagnostic/outdated-reporting-data', {
                templateUrl: MP_SITE_URL + '/advancedreports/hostDiagnosticView/agentNotRunRecently',
                controller: healthDiagnosticController
            });

           $routeProvider.when('/health-diagnostic/duplicate-hostnames', {
                templateUrl: MP_SITE_URL + '/advancedreports/hostDiagnosticView/hostsUsingSameName',
                controller: healthDiagnosticController
           });

           // redirects from old health diagnostic reports URLs to new ones
           $routeProvider.when('/health-diagnostic/hosts-using-same-name', {redirectTo: '/health-diagnostic/duplicate-hostnames'});
           $routeProvider.when('/health-diagnostic/agent-not-run-recently', {redirectTo: '/health-diagnostic/outdated-reporting-data'});
           $routeProvider.when('/health-diagnostic/hosts-never-collected', {redirectTo: '/health-diagnostic/missing-reporting-data'});
           $routeProvider.when('/health-diagnostic/hosts-using-same-identity', {redirectTo: '/health-diagnostic/duplicate-ids'});
           $routeProvider.when('/health-diagnostic/last-agent-run-unsuccessful', {redirectTo: '/health-diagnostic/policy-errors'});
           $routeProvider.when('/health-diagnostic/not-recently-collected', {redirectTo: '/health-diagnostic/unreachable-hosts'});

           $routeProvider.when('/compliance', {
                templateUrl: MP_SITE_URL + '/advancedreports/compliance_report/index',
                controller: complianceMainController
           });

           $routeProvider.when('/compliance/add_report', {
                templateUrl: MP_SITE_URL + '/advancedreports/compliance_report/add',
                controller: complianceCreateEditController
           });

           $routeProvider.when('/compliance/edit_conditions', {
                templateUrl: MP_SITE_URL + '/advancedreports/compliance_report/edit_conditions',
                controller: complianceCreateEditController
           });

           $routeProvider.when('/compliance/import', {
                templateUrl: MP_SITE_URL + '/advancedreports/compliance_report/import',
                controller: complianceImportController
           });

           $routeProvider.when('/compliance/run', {
               templateUrl: MP_SITE_URL + '/advancedreports/compliance_report/result',
               controller: complianceResultController
           });

           $routeProvider.when('/compliance/run/:reportid', {
               templateUrl: MP_SITE_URL + '/advancedreports/compliance_report/result',
               controller: complianceResultController
           });

           $routeProvider.when('/compliance/edit/:editReportId', {
               templateUrl: MP_SITE_URL + '/advancedreports/compliance_report/add',
               controller: complianceCreateEditController
           });

            /*
             * Default  - show reports list
             */
            // $routeProvider.otherwise({redirectTo: '/index'});
            $routeProvider.otherwise({
                templateUrl: MP_SITE_URL + '/advancedreports/partials/listreports',
                controller: indexController
            });

            // configure html5 to get links working
            // If you don't do this, you URLs will be base.com/#/home rather than base.com/home
            $locationProvider.html5Mode(true);
        }
);

reports.factory('authHttpResponseInterceptor', ['$q', '$location', function ($q) {
    return {
        response: function (response) {
            if (response.status === 401) {
                unAuthorizedHandler();
            }
            return response || $q.when(response);
        },
        responseError: function (rejection) {
            if (rejection.status === 401) {
                unAuthorizedHandler();
            }
            return $q.reject(rejection);
        }
    }
}]);

// redirect from /advancedreports#/path to /reports/path
reports.factory('redirectInterceptor', ['$q', function ($q) {
    return {
        response: function (response) {
            const regex = new RegExp('\/advancedreports(\/|)');
            if (regex.test(window.location.pathname)) {
                const newLocation = window.location.hash.length > 0 ?
                    `/reports/${window.location.hash.replace('#/', '')}` : // remove #/ from hash
                    '/reports/';
                window.location.href = newLocation;
                return
            }
            return response || $q.when(response);
        }
    }
}]);

reports.config(['$httpProvider', '$provide', function($httpProvider, $provide) {
        //This header was removed from recent version of angular.
        // PHP looks at this header to separate request between regular and AJAX.
        $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
        // IE fix to prevent caching
        $httpProvider.defaults.headers.common["If-Modified-Since"] = 0;
        // add interceptor to httpProvider
        $httpProvider.interceptors.push('authHttpResponseInterceptor');

        $httpProvider.interceptors.push('redirectInterceptor');


        $provide.decorator('$exceptionHandler',
        ['$delegate', errorLogger]);
}]);


function errorLogger($delegate) {
    return function (exception, cause) {
        $delegate(exception, cause);
        var msg = exception.message + "\n" + exception.stack;
        globalLogger.sendErrorToServer(msg)
    };
}



reports.directive('testforlast', function() {
    return function(scope, element, attrs) {
        scope.$watch('$last', function(v) {
            if (v) {
                addUserLabelClass();
            }
        });
    };
});

window.reports = reports;
