// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['fs/presenter/settings/LicensePresenter',
        'fs/model/settings/LicenseModel',
        'hp/core/Localizer',
        'hp/core/UrlFragment',
        'hp/core/Style',
        'hp/model/Session',
        'fs/view/common/CommonDisplayView',
        'jquery',
        'hp/lib/jquery.hpDonut',
        'hp/lib/jquery.hpGridPanels'],
    function(presenter,
             model,
             localizer,
             urlFragment,
             style,
             session,
             commonDisplayView) {  "use strict";

    var LicenseMoreView = (function() {

        var FIRST_ROW = '.hp-grid-panels .hp-grid-row:eq(0)',
            SECOND_ROW = '.hp-grid-panels .hp-grid-row:eq(1)',
            SUMMARY_GRID_PANEL='#fs-settings-license-summary-gridPanels',
            SUMMARY_GRID_PANEL_TEMPLATE = '#fs-settings-license-summary-gridPanel',
            SUMMARY_DONUT_PREFIX='#fs-settings-license-summary-donut-content',
            LICENSED_NODES='#fs-settings-license-summary-licensedNodes',
            AVAILABLE_LICENSES='#fs-settings-license-summary-availableLicenses',
            TOTAL_LICENSES='#fs-settings-license-summary-totalLicenses',
            LICENSED_REQUIRED = '#fs-settings-license-summary-licensedRequired',
            PEAK_USAGE = '#fs-settings-license-summary-peakUsage',
            SHOW_VIEW = '.hp-details-show-view',
            GRID_PANELS = '.hp-grid-panels',
            SPLASH_PAGE = '.hp-page-splash',
            WARNINIG = style.statusColor('warning'),
            OK = style.summaryColor(0),
            GRID_WIDTH = 12,
            GRID_HEIGHT = 12,
            MAXPANELS_PER_ROW = 3;

        function LicenseMoreView() {

            var summaryPanelTemplate = null,
                gridPanelsAvailable = true,
                spanClasses,
                heightClasses;

            // Create the list of hp-grid-span-* class names so we can easily remove them
            // all from an element later.
            for (var i = 1; i <= GRID_WIDTH; i++) {
                spanClasses += 'hp-grid-span-' + i + ' ';
                heightClasses += 'hp-grid-height-' + i + ' ';
            }

            /**
             * @public Creates license count link to server-hardware page
             * @param licensedProduct
             */
            function createCountLink(licensedProduct){
                var displayValue = 'instance',
                    link = null,
                    linkPage = null,
                    linkView = null,
                    linkCategory = null,
                    linkPermission = null;

                if (presenter.getConfigValue("configFile") != 'disable'){
                     displayValue = presenter.getConfigValue("displayValue");
                     linkPage = presenter.getConfigValue("linkPage");
                     linkView = presenter.getConfigValue("linkView");
                     linkCategory = presenter.getConfigValue("linkCategory");
                     linkPermission = presenter.getConfigValue("linkPermission");
                }
                if (!displayValue){
                    displayValue = 'instance';
                }
                displayValue = displayValue.toString().toLowerCase();
                var key = 'fs.settings.license.summary.type.' + displayValue;

                if ((licensedProduct.consumedCapacity !== 1) && localizer.hasValueForKey(key + '_plural')) {
                    displayValue = localizer.getString(key + '_plural');
                }
                link = getLink(displayValue, linkPage, linkView, linkCategory, linkPermission, licensedProduct);

                return link;
            }

            function getLink(displayValue, linkPage, linkView, linkCategory, linkPermission, licensedProduct){
                var link = localizer.getString('fs.settings.license.summary.licensed_total_nodes',
                    [licensedProduct.consumedCapacity,displayValue]);

                if (linkPage && linkView && linkCategory && linkPermission){
                    if (session.canPerformAction(linkCategory, linkPermission) && licensedProduct.consumedCapacity > 0){
                        var location = urlFragment.createFragment(linkPage,
                            linkView, null, null,  ['f_suri=' + licensedProduct.uri,'f_an=license-entitlement']);
                            link = $('<a></a>').attr('href',location).text(link);
                    }
               }
               return link;
           }
            /**
             * @private Adds hp-grid-panels
             *
             */
            function addGridPanels(){
                var panels = $('<div></div>').addClass('hp-grid-panels');
                panels.attr('id', SUMMARY_GRID_PANEL.slice(1));
                var row = $('<div></div>').addClass('hp-grid-row');
                panels.append(row);
                panels.append(row);
                $(SHOW_VIEW).append(panels);
                gridPanelsAvailable = true;
            }
            /**
             * @private Removes hp-grid-panels
             *
             */
            function removeGridPanels(){
                $(GRID_PANELS).remove();
                gridPanelsAvailable = false;
            }

            /**
             * @public Creates Add button linking to addLicense Dialog
             *
             */
            function createAddButton(){
                var anchor = $('<a></a>').attr('href', "#/settings/add/license");
                anchor.text(localizer.getString('fs.settings.license.summary.add'));
                return $('<div></div>)').addClass('hp-add-link').append(anchor).html();
            }

            /**
             * @private Add Splash page with hyperlink to add license
             *
             */
            function addEmptyPageSplash(){
                var splash = $('<div></div>').addClass('hp-page-splash');
                var addButton = createAddButton();
                var empty = $('<div></div>').addClass('hp-page-empty').
                    text(localizer.getString('fs.settings.license.summary.no_licenses'));
                splash.append(empty);
                splash.append(addButton);
                $(SHOW_VIEW).append(splash);
            }

            /**
             * @private Remove Splash page
             *
             */
            function removeEmptyPageSplash(){
                $(SPLASH_PAGE).remove();
            }

            /**
             * @public Handle failed validation by printing error messages
             */
            function onGetLicenseSummaryError(errorInfo) {
                removeGridPanels();
                addEmptyPageSplash();
            }

            /**
             * @public Handle failed validation by printing error messages
             */
            function onGetLicenseConfigSuccess() {
                presenter.updateLicensesummary();
            }
             /**
             * @public Handle failed validation by printing error messages
             */
            function onGetLicenseConfigError(errorInfo) {
                presenter.updateLicensesummary();
            }
            /**
             * display license Summary table
             * @private
             */
            function onGetLicenseSummarySuccess() {
                var licenseSummary = presenter.getLicensesummary();

                if (!licenseSummary){
                    removeGridPanels();
                    removeEmptyPageSplash();
                    addEmptyPageSplash();
                    return;
                }

                if (!gridPanelsAvailable){
                    removeEmptyPageSplash();
                    addGridPanels();
                    $(SUMMARY_GRID_PANEL).hpGridPanels();
                }
                var panelsPerRow = licenseSummary.count < MAXPANELS_PER_ROW ? licenseSummary.count : MAXPANELS_PER_ROW,
                    span = Math.floor(GRID_WIDTH / panelsPerRow),
                    height = licenseSummary.count < MAXPANELS_PER_ROW ? GRID_HEIGHT : GRID_HEIGHT/2;

                $.each(licenseSummary.members, function(index, licensedProduct) {
                    var uri = licensedProduct.uri ? licensedProduct.uri : index;
                    var dataUri = '[data-uri="' + uri + '"]';
                    var name = licensedProduct.product;
                    var row = (index >= MAXPANELS_PER_ROW) ? SECOND_ROW : FIRST_ROW;
                    //checking product has licensed or node assinged.
                     if(licensedProduct.unlicensedCount === 0 &&
                         licensedProduct.totalCapacity === 0 ){
                         return null;
                       }
                    // If panel exists, don't create new ones. update the numbers.
                    if(!$(SUMMARY_DONUT_PREFIX + dataUri).length > 0 ){
                        var summaryPanel = summaryPanelTemplate.clone();
                        $(":header", summaryPanel).html(name);

                        $(SUMMARY_DONUT_PREFIX, summaryPanel).attr('data-uri', uri);
                        $(LICENSED_NODES, summaryPanel).attr('data-uri', uri);
                        $(LICENSED_REQUIRED, summaryPanel).attr('data-uri', uri);
                        $(PEAK_USAGE, summaryPanel).attr('data-uri', uri);
                        $(TOTAL_LICENSES, summaryPanel).attr('data-uri', uri);
                        $(AVAILABLE_LICENSES, summaryPanel).attr('data-uri', uri);

                        $('p', summaryPanel).html(localizer.getString('fs.settings.license.summary.compliance'));

                        $(row).append(summaryPanel);
                    }

                    if(licensedProduct.unlicensedCount === 0){
                        $(LICENSED_REQUIRED + dataUri).hide();
                    }else{
                        var key = 'fs.settings.license.summary.type.license';
                        if ((licensedProduct.unlicensedCount !== 1)) {
                            key = key + '_plural';
                        }
                        $(LICENSED_REQUIRED + dataUri).html(localizer.getString('fs.settings.license.summary.license_required',
                            [licensedProduct.unlicensedCount,localizer.getString(key)]));
                        $(LICENSED_REQUIRED + dataUri).show();
                    }
                    $(LICENSED_NODES + dataUri).html(createCountLink(licensedProduct));
                    if (licensedProduct.hwm === undefined ){
                        $(PEAK_USAGE + dataUri).hide();
                        $(TOTAL_LICENSES + dataUri).hide();
                        var key = 'fs.settings.license.summary.type.license';
                        if ((licensedProduct.availableCapacity !== 1)) {
                            key = key + '_plural';
                        }
                        $(AVAILABLE_LICENSES + dataUri).html(localizer.getString('fs.settings.license.summary.available_license',
                            [licensedProduct.availableCapacity,localizer.getString(key)]));
                        $(AVAILABLE_LICENSES + dataUri).show();
                    }
                    else{
                        $(AVAILABLE_LICENSES + dataUri).hide();
                        $(LICENSED_REQUIRED + dataUri).hide();
                        $(PEAK_USAGE + dataUri).html(localizer.getString('fs.settings.license.summary.peak_usage',
                            [licensedProduct.hwm]));
                        $(PEAK_USAGE + dataUri).show();
                        $(TOTAL_LICENSES + dataUri).html(localizer.getString('fs.settings.license.summary.total_license',
                            [licensedProduct.totalCapacity]));
                        $(TOTAL_LICENSES + dataUri).show();
                    }

                    if(licensedProduct.consumedCapacity === 0 &&
                        licensedProduct.unlicensedCount === 0){
                        $.hpDonut($(SUMMARY_DONUT_PREFIX + dataUri), []);
                    }
                    else {
                        var percentageCompliance = Math.floor(licensedProduct.percentageCompliance);
                        var nonCompliance = (100 -percentageCompliance);
                        if(percentageCompliance > 0 && percentageCompliance < 100){
                            $.hpDonut($(SUMMARY_DONUT_PREFIX + dataUri), [
                               {label: {value: ''+percentageCompliance+'%',
                                   text: ''},
                                   color: OK, data: percentageCompliance},
                               {label: {value: ''+nonCompliance+'%',
                                   text: localizer.getString('fs.settings.license.summary.licensed_instance_required',[licensedProduct.product])},
                                   color: WARNINIG, data: nonCompliance}
                            ]);
                        }else{
                            $.hpDonut($(SUMMARY_DONUT_PREFIX + dataUri), [
                                {label: {value: ''+percentageCompliance+'%',
                                    text: ''},
                                    color: OK, data: percentageCompliance},
                                {label: {value: ''+percentageCompliance+'%',
                                    text: ''},
                                    color: WARNINIG, data: nonCompliance}
                            ]);
                        }
                    }

                });

                $('.hp-grid-panel').removeClass(spanClasses)
                    .addClass('hp-grid-span-' + Math.max(1,span));
                $('.hp-grid-panel').removeClass(heightClasses)
                    .addClass('hp-grid-height-' + Math.max(1,height));
                $(SUMMARY_GRID_PANEL).hpGridPanels('reset');

            }

            this.pause = function () {
                model.setPollingEnabled(false);
                presenter.off('licenseSummaryChange', onGetLicenseSummarySuccess);
                presenter.off('licenseSummaryError', onGetLicenseSummaryError);
                presenter.off('licenseConfigChange', onGetLicenseConfigSuccess);
                presenter.off('licenseConfigError', onGetLicenseConfigError);
            };

            this.resume = function() {
                model.setPollingEnabled(true);
                presenter.on('licenseSummaryChange', onGetLicenseSummarySuccess);
                presenter.on('licenseSummaryError', onGetLicenseSummaryError);
                presenter.on('licenseConfigChange', onGetLicenseConfigSuccess);
                presenter.on('licenseConfigError', onGetLicenseConfigError);
                removeGridPanels();
                presenter.updateLicensesummary();
                if(gridPanelsAvailable){
                    $(SUMMARY_GRID_PANEL).hpGridPanels('reset');
                }
                commonDisplayView.manageDisplayInOverviewDropdown();
            };


            this.init = function() {
                $(SUMMARY_GRID_PANEL).hpGridPanels();
                summaryPanelTemplate = $(SUMMARY_GRID_PANEL_TEMPLATE).detach().
                    removeAttr('id').removeClass('hp-template');
                presenter.init();
                this.resume();
            };
    }

    return new LicenseMoreView();

  }());

  return LicenseMoreView;

});