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

define(['fs/services/settings/LicenseService',
        'fs/services/settings/ApplianceService',
        'hp/core/EventDispatcher',
        'hp/model/DevelopmentSettings',
        'hp/services/Log',
        'hp/lib/date',
        'jquery'],
function(licenseService, applianceService, EventDispatcher, settings, log) { "use strict";

    var LicenseModel = (function() {

        function LicenseModel() {

            // derive from EventDispatcher
            EventDispatcher.call(this);
            var pollingEnabled = false,
                configValue = null,
                updateTimer = null,
                licenseSummary = null,
                updateSummaryVer = false,
                self = this,
                configMap = { },
                lastStatus = { };

            function resetUpdateTimer() {
                if (updateTimer) {
                    clearTimeout(updateTimer);
                    updateTimer = null;
                }
                if (licenseSummary && pollingEnabled) {
                    updateTimer = setTimeout(function() {
                        if (pollingEnabled) {
                            self.updateLicenseSummary();
                        }
                    }, settings.getRefreshInterval());
                }
            }

            function updateLicenseStatus(licenseSummary) {

                var underlicensed = $.grep(licenseSummary.members, function(licensedProduct, index) {
                    return licensedProduct.unlicensedCount > 0;
                });

                lastStatus = {
                    status : {
                        needMoreLicense : underlicensed.length > 0,
                        underlicensed : underlicensed
                    },
                    updated: (new Date()).toISOString()
                };
                self.fire('licenseStatusChange', lastStatus);

            }

            function updateLicenseStatusError(errorInfo) {
                self.fire('licenseStatusChange', lastStatus);
            }

            function onGetConfigValuesSuccess(configdata) {
                if (configdata.members){
                    var displayValue = 'instance';
                    $.each(configdata.members, function(index, names) {
                        switch (names.name) {
                            case 'licenses.compliance.strategy' :
                                configValue = names.value;
                                break;
                            case 'licenses.resource.display.name' :
                                displayValue = names.value;
                                if (displayValue.toString().toLowerCase() !== "instance" &&
                                       displayValue.toString().toLowerCase() !== "node" &&
                                       displayValue.toString().toLowerCase() !== "vm" &&
                                       displayValue.toString().toLowerCase() !== "server"){
                                    displayValue = 'instance';
                                }
                                configMap.displayValue = displayValue;
                                break;
                            case 'licenses.link.page' :
                                configMap.linkPage = names.value;
                                break;
                            case 'licenses.link.view' :
                                configMap.linkView = names.value;
                                break;
                            case 'licenses.category' :
                                configMap.linkCategory = names.value;
                                break;
                            case 'licenses.permission' :
                                configMap.linkPermission = names.value;
                                break;
                           }
                    });
                    if(configValue === "high-water-mark"){
                        updateSummaryVer = true;
                    }
                }
                else{
                    configMap.configFile = 'disable';
                }
                self.fire('licenseConfigChange');
              }

            function onGetLicenseSummarySuccess(summary) {
                var count=0;
                licenseSummary = summary;
                if (licenseSummary){
                    $.each(licenseSummary.members, function(index, licensedProduct) {
                        if (licensedProduct.unlicensedCount === 0 &&
                            licensedProduct.totalCapacity === 0 ){
                                count=count+1;
                           }
                    });
                    if (licenseSummary.count === count){
                        licenseSummary = null;
                    }
                 }
                resetUpdateTimer();
                self.fire('licenseSummaryChange');
            }

            this.updateProductConfigValues = function() {
                applianceService.getConfigValues({
                    success: onGetConfigValuesSuccess,
                    error: onGetConfigValuesError
                });
            };

            function onGetLicenseSummaryError(errorInfo) {
                self.fire('licenseSummaryError', errorInfo);
            }

            function onGetConfigValuesError(errorInfo) {
                self.fire('licenseConfigError', errorInfo);
            }

            this.getConfigValue = function(key){
                return configMap[key];
            };

            this.setPollingEnabled = function(enabled) {
                pollingEnabled = enabled;
                resetUpdateTimer();
            };

            /**
             * Retrieves the last known license status
             */
            this.getLicenseStatus = function () {
                return lastStatus;
            };

           this.updateLicenseSummary = function(){
               if (!updateSummaryVer){
                   licenseService.getLicenseSummary({
                       success: onGetLicenseSummarySuccess,
                       error: onGetLicenseSummaryError
                   });
               }
               else{
                   licenseService.getLicenseSummaryVer({
                       success: onGetLicenseSummarySuccess,
                       error: onGetLicenseSummaryError
                   });
               }
            };

            this.updateLicenseStatus = function() {
                licenseService.getLicenseSummary({
                    success: updateLicenseStatus,
                    error: updateLicenseStatusError
                });
            };

            /**
             * @returns licenseSummary
             */
            this.getLicenseSummary = function () {
                return licenseSummary;
            };
        }
        return new LicenseModel();
    }());
    return LicenseModel;
});
