// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['fs/model/settings/LicenseModel',
        'hp/core/Notifications',
        'fs/services/alerts/AlertsService',
        'hp/core/Router',
        'hp/core/Localizer',
        'hp/model/Session',
        'jquery'],
function(licenseModel, notifications, alertsService, router, localizer, session) { "use strict";

    var LicenseNotifier = (function() {

        var CHECK_INTERVAL = 48 * 60 * 60 * 1000; // 48 hours in msecs
        function LicenseNotifier() {

            var notified = false;
            var warned = false;
            var licenseStatus = null;

            /**
             * @private
             * Get the alerts for the given alertTypeIDs.
             * Takes either an array of alertTypeIDs or a
             * single alertTypeID as an argument.
             */
            function getAlerts(alertTypeIDs, handlers) {
                var count = 1,
                    sort = null,
                    queryStrings = [ "alertState!='Cleared'"];

                if(typeof alertTypeIDs === 'string') {
                    alertTypeIDs = [alertTypeIDs];
                }

                alertTypeIDs = $.map(alertTypeIDs, function(alertTypeID) {
                    return "alertTypeID='" + alertTypeID + "'";
                });

                queryStrings.push(alertTypeIDs.join(" OR "));

                alertsService.getAlertsByQuery(
                    queryStrings,
                    count,
                    sort,
                    handlers
                );
            }

            function updateNotification() {
                licenseStatus = licenseModel.getLicenseStatus();

                if (!notified && !$.isEmptyObject(licenseStatus) &&
                    ($('#hp-activity-notification').length > 0)) {
                    notified = true;

                    if (licenseStatus.status.needMoreLicense ) {
                       var product = [],
                           name = localizer.getString('fs.settings.license.config.add_license');

                       $.each(licenseStatus.status.underlicensed, function(index, underLicensedProduct) {
                           product.push(underLicensedProduct.product);
                       });
                       var link = localizer.getString('fs.settings.license.config.add_license');
                       if(session.canPerformAction('licenses','Create')) {
                           link = '\n\n[' + name + '](#/settings/add/license)';
                       }

                        notifications.add({
                                status:'warning',
                                uri: 'licensecheck',
                                summary: localizer.getString('fs.settings.license.notification.title'),
                                details: localizer.getString('fs.settings.license.notification.details',
                                         [product.join()]) + link}, true);
                        warned = true;
                    }
                    else {
                        if (warned) {
                            // only update the notification if there is one
                            notifications.add({
                                status:'ok',
                                uri: 'licensecheck',
                                summary: localizer.getString('fs.settings.license.notification.license_ok'),
                                details: ''
                            }, false);
                        }
                    }

                }
            }

            function updateLicenseStatus() {
                notified = false;
                getAlerts("licenses.overconsumed", {
                    success: function(alerts){
                        if (alerts.total !== 0){ // There are alerts
                            licenseModel.updateLicenseStatus();
                        }
                    }
                });
            }

            this.init = function () {
                // Every time the route changes check if we need to notify
                router.watch('license notifier', '^.*', { change: updateNotification });

                licenseModel.on('licenseStatusChange', updateNotification);
                setInterval(updateLicenseStatus, CHECK_INTERVAL);

                // get the licenseData first time. Normally this should be done by
                // the code that checks licensing before login.
                updateLicenseStatus();
                // otherwise could just do:
                //updateNotification()
            };
        }
        return new LicenseNotifier();
    }());
    return LicenseNotifier;
});