'use strict';

/* Directives */
dashboardApp.directive('notifications', ['notificationService', '$timeout', function (notificationService, $timeout) {
    return {
        restrict: 'A',

        template: '<div id="notification_block" ng-repeat="(type, notification) in notificationsList">' +
        '<div ng-if="type==\'error\'"   class="alert alert-error">{{notification.text}}</div>' +
        '<div ng-if="type==\'success\'" class="alert alert-info">{{notification.text}}</div>' +
        '<div ng-if="type==\'warning\'" class="alert alert-warning">{{notification.text}}</div>' +
        '</div>',

        link: function ($scope, $elm, $attrs) {
            $scope.$on('setNotification', function () {
                $scope.notificationsList = notificationService.getNotifications();
                if ($(".alert-info")) {
                    // make sure it displays again for multiple actions after initial fadeTo
                    $(".alert-info").fadeTo(0, 1);
                }

                if ($scope.modalOpen === undefined || $scope.modalOpen.status === false) {
                    window.scrollTo(null, (angular.element("#notification_block_wrapper").position().top - 40));
                    $timeout(function () {
                        if ($(".alert-info")) {
                            //check for alert-info, fade and hide if exists
                            $(".alert-info").fadeTo(500, 0).slideUp(500);
                        }
                    }, 5000);
                }
            });

            $scope.$on('resetNotificationMessage', function () {
                $scope.notificationsList = {};
            });

            $scope.$on('hideNotification', function () {
                $(".alert-info").slideUp(0);
            });

            $scope.$on('modalOpen', function () {
                $scope.modalOpen = {'status': true};
            });


            $scope.$on('modalClose', function () {
                $scope.modalOpen = {'status': false};
            });
        }
    };
}]);

dashboardApp.directive('donutInner', function () {
    return {
        restrict: 'C',
        scope: true,
        link: function (scope, elem, attrs) {
            scope.$watch('widget.severityStat', function () {
                var percent = 0;

                var numFails = 0;
                var numHosts = 0;
                if (scope.widget.severityStat) {

                    if (elem.hasClass('high')) {
                        numFails = scope.widget.severityStat.high.failHosts;
                        numHosts = scope.widget.severityStat.high.totalHosts;
                    } else if (elem.hasClass('medium')) {
                        numFails = scope.widget.severityStat.medium.failHosts;
                        numHosts = scope.widget.severityStat.medium.totalHosts;
                    } else if (elem.hasClass('low')) {
                        numFails = scope.widget.severityStat.low.failHosts;
                        numHosts = scope.widget.severityStat.low.totalHosts;
                    }
                }

                percent = (numFails / numHosts) * 360 || 0;

                // minimum roation is 3 deg for visual reasons
                percent = (percent > 0 && percent < 3) ? 3 : percent;

                elem.css('-moz-transform', 'rotate(' + percent + 'deg)');
                elem.css('-webkit-transform', 'rotate(' + percent + 'deg)');
                elem.css('-o-transform', 'rotate(' + percent + 'deg)');
                elem.css('transform', 'rotate(' + percent + 'deg)');
                elem.css('clip', 'rect(0px,' + (elem.outerWidth(false) / 2 + .5) + 'px,' + (elem.outerHeight(false) + 1) + 'px, 0px)');
            }, true);
        }
    }
});

dashboardApp.directive('donutFill', function () {
    return {
        restrict: 'C',
        scope: true,
        link: function (scope, elem, attrs) {
            scope.$watch('widget.severityStat', function () {

                var numFails = 0;
                var numHosts = 0;
                if (scope.widget.severityStat) {

                    if (elem.hasClass('high')) {
                        numFails = scope.widget.severityStat.high.failHosts;
                        numHosts = scope.widget.severityStat.high.totalHosts;
                    } else if (elem.hasClass('medium')) {
                        numFails = scope.widget.severityStat.medium.failHosts;
                        numHosts = scope.widget.severityStat.medium.totalHosts;
                    } else if (elem.hasClass('low')) {
                        numFails = scope.widget.severityStat.low.failHosts;
                        numHosts = scope.widget.severityStat.low.totalHosts;
                    }
                }


                if ((numFails / numHosts * 100) > 50) {
                    elem.show();
                    elem.css('clip', 'rect(0px,' + (elem.outerWidth(false) + 1) + 'px,' + (elem.outerHeight(false) + 1) + 'px, ' + elem.outerWidth(false) / 2 + 'px)');
                } else {
                    elem.hide();
                }
            }, true);
        }
    }
});

dashboardApp.directive('onboardWizard', ['$rootScope', function ($rootScope) {
    return {
        restrict: 'C',
        templateUrl: MP_SITE_URL + '/directives/partials/directive_onboardwizard.php',
        scope: true,
        link: function (scope, element, attr) {

            var options = {
                showCancel: true,
                keyboard: true,
                buttons: {
                    cancelText: 'Close',
                    nextText: 'Next',
                    submitText: 'Get started!'
                }
            };

            var el = angular.element(document.querySelector('#wizard-modal'));
            var wizard = el.wizard(options);
            wizard.on('submit', function () {
                wizard.close();
                $rootScope.$broadcast('welcomeWizardClosed');
            });

            wizard.on('closed', function () {
                $rootScope.$broadcast('welcomeWizardClosed');
            });

            scope.$watch('showModal', function () {
                if (scope.showModal) {
                    wizard.cancelButton.show();
                    wizard.show();
                    modalThreshold.setShownTime();
                }
            });
        }
    };
}]);

dashboardApp.directive('tourGuide', ['$rootScope', function ($rootScope) {
    return {
        restrict: 'C',
        templateUrl: MP_SITE_URL + '/directives/partials/tour_guide.php',
        scope: true,
        link: function (scope, element, attr) {

            var options = {
                keyboard: true,
                contentHeight: 550,
                buttons: {
                    submitText: 'Close',
                    backText: ''
                }
            };

            var el = angular.element(document.querySelector('#tour-modal'));
            var tour = el.wizard(options);
            tour.on('submit', function () {
                tour.close();
            });

            tour.on('closed', function () {
                $rootScope.$broadcast('tourModalClosed');
            });

            scope.$watch('showTourModal', function () {
                if (scope.showTourModal) {
                    $(".wizard-back").hide();
                    tour.cancelButton.show();
                    tour.show();
                    modalThreshold.setShownTime();
                }
            });
        }
    };
}]);


dashboardApp.directive('chozen', function () {
    var linker = function (scope, element, attr) {
        if (attr.search === "false") {
            element.chosen({disable_search_threshold: 9999});
        } else {
            element.chosen();
        }
        if (attr.conditions === "true") {
            element.prepend("<option value='' style='border-bottom: 1px #e7e7e7 solid;padding:6px 0 8px 5px; margin-bottom:4px'>Create new condition</option>");
            element.on('change', function (evt, params) {
                if (params.selected == "") {
                    // update placeholder text
                    updatePlaceholder("Create new condition");
                }
            });
            var updatePlaceholder = function (string) {
                scope.conditionsPlaceholder = string;
                scope.$apply();
                element.trigger('chosen:updated');
            }
        }
        scope.$watchCollection(attr.watch, function () {
            element.trigger('chosen:updated');
        })
        scope.$watch(attr.ngModel, function () {
            element.trigger('chosen:updated');
        })
        scope.$watch(attr.disable, function (newValue) {
            var val = newValue || false;
            element.prop('disabled', val);
            element.trigger('chosen:updated');
        })
    }
    return {
        restrict: 'A',
        link: linker
    }
});

dashboardApp.directive('scriptEvent', function () {
    var linker = function (scope, element, attr) {
        var str = scope.event.item_name;
        scope.strArray = [];
        if (str.indexOf('->') != -1) {
            scope.strArray = str.split('->');
            angular.forEach(scope.strArray, function (value, key) {
                scope.strArray[key] = '"' + value + '"';
            });
        } else {
            scope.strArray[0] = '"' + str + '"';
        }
    }
    return {
        restrict: 'A',
        link: linker,
        template: '{{event.item_type}} {{strArray[0]}} <span ng-show="event.status==\'success\'">successful</span><span ng-show="event.status==\'fail\'">failed</span> for alert {{strArray[1]}}.'
    }
});

/*
 This directive allows us to pass a function in on an enter key to do what we want.
 */
dashboardApp.directive('enterPress', function () {
    var linker = function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.enterPress);
                });

                event.preventDefault();
            }
        });
    }
    return {
        restrict: 'A',
        link: linker
    }
});

dashboardApp.directive('licenseReminder', ['$modal', '$http', '$cookies', '$rootScope', 'dashboardService', '$q', function ($modal, $http, $cookies, $rootScope, dashboardService, $q) {
    return {
        restrict: 'E',

        scope: true,
        link: function (scope, element, attrs) {
            var $modalInstance,
                licenseUrl = MP_SITE_URL + '/licenses/status',
                dayRemindersStart = 90,
                dayRemindersInterval = 30;

            processLicenseReminder();

            $rootScope.$on('welcomeWizardClosed', function (event, data) {
                processLicenseReminder();
            });

            /**
             * Check if should be shown license reminder.
             */
            function processLicenseReminder(){
                getLicenseData().then(function(data){
                    var licenseData = data;
                    licenseData.daysLeft = calculateDaysLeft(licenseData['expiry']);
                    /**
                     * Show license reminder
                     *
                     * Conditions:
                     * License granted more than 25. less than 25 - is free.
                     * License days left less than 90.
                     * This modal window didn't show before or user clicked "don't show" button.
                     */
                    if(
                        licenseData.licenseGranted > 25 &&
                        (licenseData.daysLeft < dayRemindersStart && !$cookies['licenseReminderHide']) &&
                        (sessionStorage['seenLicenseReminder'] !== "true")
                    ){
                        sessionStorage['seenLicenseReminder'] = true;
                        openModal(licenseData, 'licenseReminder', 'licenseReminderHide');
                    }

                    /**
                     * Show license limit exceeded reminder
                     *
                     * Conditions:
                     * Licenses utilized more than licenses granted
                     * User haven't seen yet this modal during the session
                     */
                    if (
                        parseInt(licenseData.utilized) > parseInt(licenseData.licenseGranted) &&
                        sessionStorage['seenUtilizationReminder'] !== "true"
                    ) {
                        sessionStorage['seenUtilizationReminder'] = true;
                        licenseData.licenseOwner = licenseData.licenseOwner || 'n/a';
                        openModal(licenseData, 'overUtilizationLicenseReminder');
                    }
                });
            }

            /**
             * Get information about license
             * @returns {*}
             */
            function getLicenseData(){
                return $http({
                    method: 'get',
                    url: licenseUrl,
                    dataType: 'json',
                    cache: false
                }).then(function(response){
                    return response.data;
                });
            }

            /**
             * Open modal with information
             */
            function openModal(data, fileName){
                $modalInstance = $modal.open({
                    templateUrl: MP_SITE_URL + `/directives/partials/${fileName}.php`,
                    scope: scope,
                    controller: function ($scope, $modalInstance) {
                        $scope.licenseData = data;
                        $scope.options = {};
                        $scope.options.licenseReminderHideCookie = false;

                        $scope.close = function () {
                            if($scope.options.licenseReminderHideCookie === true){
                                var date = new Date();
                                date.setDate(date.getDate() + dayRemindersInterval);
                                document.cookie = 'licenseReminderHide=true;expires='+date+';';
                            }
                            $modalInstance.close('cancel');
                        };
                    }
                });
            }
        }
    };
}]);