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

define(['hp/presenter/dashboard/DashboardCategoryPresenter',
    'hp/core/LinkTargetBuilder',
    'hp/core/Style',
    'hp/model/Session',
    'hp/core/Localizer',
    'jquery',
    'hp/lib/jquery.hpTimestamp',
    'hp/lib/jquery.hpPlot',
    'lib/jquery.flot.pie',
    'hp/lib/jquery.hpDonut'],
function(DashboardCategoryPresenter, linkTargetBuilder, style, session, localizer) { "use strict";

    var DashboardCategoryView = (function() {
      
        var DEFAULT_STATUSES = [
                        {status:'error', value:'CRITICAL'},
                        {status:'warning', value: 'MAJOR'},
                        {status:'ok', value: 'OK'}
                    ];
        
        /**
         * Constructor
         */
        function DashboardCategoryView() {
          
            var presenter;
            var container;
            var configuration;
            var registered = false;
            var category;
          
            function checkCanAdd(total) {
                if (configuration.addLinkLabel) {
                    if (configuration.canAdd) {
                        configuration.canAdd(total, function (canAdd) {
                            $('.hp-primary', container).parent().toggle(canAdd);
                        });
                    }
                    else if (session.canPerformAction(configuration.category, 'Create')) {
                        var haveItems = (total > 0);
                        $('.hp-primary', container).parent().toggle(!haveItems);
                    }
                }
            }
            
            function onSummaryChange(summary) {
                var link = linkTargetBuilder.makeLink(null, null, null, summary.category,
                        null, null, ['freset=true']);
                var haveItems = (summary.total > 0);
                
                $('.hp-summary-status', container).toggle(haveItems);
                $('.hp-utilization-summary', container).toggle(haveItems);
                $('.hp-dashboard-value', container).toggle(!haveItems);
                checkCanAdd(summary.total);
                
                // TODO: use MainMenu to get label
                $('header .hp-name', container).
                    text(linkTargetBuilder.categoryLabel(summary.category));
                $('header .hp-count', container).text(summary.total);
                if (link) {
                    $('header h2 a', container).
                        attr('href', $(link).attr('href')).
                        removeClass('hp-inactive');
                } else {
                    $('header h2 a', container).addClass('hp-inactive');
                }
                $.each(configuration.statuses, function(index, status) {
                    var anchor =
                        $('.hp-summary-status a.hp-summary-' + status.status, container);
                    var icon = $('> .hp-status', anchor);
                    var link;
                    
                    $('.hp-count', anchor).text(summary[status.status]);
                    if (! summary[status.status]) {
                        icon.addClass('hp-unset');
                        anchor.removeAttr('href').addClass('hp-inactive');
                    } else {
                        icon.removeClass('hp-unset');
                        link = linkTargetBuilder.makeLink(
                            null, null, null,
                            summary.category, null, null,
                            ['f_q=status:' + status.value]);
                        if (link) {
                            anchor.attr('href', $(link).attr('href')).
                                removeClass('hp-inactive');
                        } else {
                            anchor.removeAttr('href').addClass('hp-inactive');
                        }
                    }
                });
            }
            
            function onUtilizationChange(utilization) {
                var data = [],
                    index = utilization.index;

                $.each(utilization.segments, function (index, segment) {
                    var color, datum;
                    var filteredLocation = null;

                    if(category) {
                        if (segment.isRemainingSegment) {
                            // get remainingSegment link  
                            if (segment.other_link) {
                                filteredLocation = segment.other_link;
                            }
                            // create remainingSegment link
                            else if(segment.query && segment.query.length > 0) {
                                filteredLocation = linkTargetBuilder.makeLocation(null, null, category, 
                                        null, ['f_q=' + segment.query]); 
                            }
                        }
                        // create non-remainingSegment link
                        else if(segment.query && segment.query.length > 0) {
                            filteredLocation = linkTargetBuilder.makeLocation(null, null, category, 
                                    null, ['f_q=' + segment.query]); 
                        }
                    }

                    if (segment.color) {
                        color = segment.color;
                    } else if (utilization.type === 'status') {
                        color = style.statusColor(segment.status);
                    } else if (index === (utilization.segments.length - 1)) {
                        color = style.summaryBaseColor();
                    } else {
                        color = style.summaryColor(index);
                    }
                    datum = {label: { text: segment.label, value: segment.total},
                        color: color, location: filteredLocation};
                    if (segment.total > 0) {
                        // ensure that enough of the segment is visible
                        datum.data = Math.max(segment.total,
                            utilization.total * 0.03);
                    } else {
                        datum.data = 0;
                    }
                    data.push(datum);
                });
                $.hpDonut($('.hp-donut-container:eq('+index+')', container), data);
                $('.hp-pie-summary:eq('+index+')', container).
                    text(utilization.label);
            }
          
            /**
             * @public
             */
            this.pause = function () {
                presenter.pause();
                presenter.off('summaryChange', onSummaryChange);
                presenter.off('utilizationChange', onUtilizationChange);
                registered = false;
            };
            
            this.resume = function () {
            	if (!registered) {
                    presenter.on('summaryChange', onSummaryChange);
                    presenter.on('utilizationChange', onUtilizationChange);
                    registered = true;
                }
                presenter.resume();
            };
            
            this.update = function () {
                presenter.update();
            };
            
            this.init = function (configurationArg, containerArg) {
                var pieTemplate = $('#hp-dashboard-category-pie-template', container).
                        remove().attr('id', '').removeClass('hp-template');
                container = containerArg;
                configuration = $.extend({statuses: DEFAULT_STATUSES}, configurationArg);
                category = configuration.category;
                presenter = new DashboardCategoryPresenter();
                presenter.init(configuration);
                
                if (! configuration.utilization) {
                    $('.hp-utilization-summary', container).hide();
                }
                else {
                    var numUtil = $.isArray(configuration.utilization) ? configuration.utilization.length : 1;
                    for (var i = 0; i < numUtil; i++) {
                        $('.hp-utilization-summary', container).append(pieTemplate.clone());
                    }
                }
                
                $('.hp-summary-status', container).hide();
                $('.hp-utilization-summary', container).hide();
                $('.hp-dashboard-value', container).hide()
                    .text(localizer.getString('core.master.noItems',
                            [linkTargetBuilder.categoryLabel(configuration.category).toLowerCase()]));
                $('.hp-primary', container).parent().hide();
                if (configuration.addLinkLabel) {
                    var addHref = $(linkTargetBuilder.makeLink(null, null, 'add', configuration.category)).attr('href');
                    $('.hp-primary', container).attr('href', addHref)
                        .text(configuration.addLinkLabel);
                }
            };
        }

        return DashboardCategoryView;
    }());
    
    return DashboardCategoryView;
});
