// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
define(['hp/core/Localizer',
        'jquery',
        'hp/lib/jquery.hpGridPanels'],
function(localizer) {"use strict";

    var SettingsOverviewView = ( function() {

        var PANELS = '.hp-grid-panels',
            FIRST_ROW = '.hp-grid-panels .hp-grid-row:eq(0)',
            SECOND_ROW = '.hp-grid-panels .hp-grid-row:eq(1)',
            MORE_LINK = 'header > h2 > a',
            SELECTOR_OPTIONS = '#hp-settings-panel-selector .hp-options',
            SELECTOR_LINKS = '#hp-settings-panel-selector a',
            GRID_WIDTH = 12,
            //GRID_HEIGHT = 12,
            DEFAULT_OPTIONS = {
                priority : 99999
            };
        /**
         * @class View script for the Overview pane of the Settings page.
         *     Delegates to the view scripts for the individual panels.
         */
        function SettingsOverviewView() {

            var panels = [],
                active = false,
                spanClasses;

            // 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 + ' ';
            }

            function panelSortCompare(a, b) {
                return (a.options.priority == b.options.priority) ? 0 :
                    ((a.options.priority > b.options.priority) ? 1 : -1);
            }


            function addToSelector(panel) {
                var moreHref,
                    panelId,
                    moreLink;

                if (! panel.addedToSelector) {

                    if ($(SELECTOR_OPTIONS).length > 0) {

                        moreHref = $(MORE_LINK, panel.panel).attr('href');
                        // If the panel has more details, add a selector link
                        // for it if there isn't one already.
                        if (moreHref &&
                            ($(SELECTOR_LINKS).filter('[href="'+moreHref+'"]').length === 0) &&
                            ($(SELECTOR_LINKS).filter('[href^="'+moreHref+'/"]').length === 0)) {
                            panelId = panel.panel.filter('.hp-grid-panel').attr('id');
                            moreLink = $('<a>').attr('href', moreHref)
                                .attr('data-panel-id', panelId)
                                .text($(MORE_LINK, panel.panel).text())
                                .addClass('hp-anchor-uri');

                            $(SELECTOR_OPTIONS).append($('<li>').append(moreLink));
                        }

                        panel.addedToSelector = true;
                    }
                }
            }

            function addPanelsToPage()
            {
                var panelsPerRow = Math.ceil(panels.length / 2),
                    span = Math.floor(GRID_WIDTH / panelsPerRow);

                $.each(panels, function(index, panel) {

                    addToSelector(panel); // in case we haven't yet

                    var row = (index >= panelsPerRow) ? SECOND_ROW : FIRST_ROW;
                    $(row).append(panel.panel);

                    if (!panel.initialized) {
                        panel.initialized = true;
                        if (panel.view.init) {
                            panel.view.init();
                        }
                    }
                });
                $('.hp-grid-panel').removeClass(spanClasses)
                    .addClass('hp-grid-span-' + Math.max(1,span));
            }

            function havePanel(newPage) {
                var newPanelId = newPage.filter('.hp-grid-panel').attr('id'),
                    id;
                for (var i = 0; i < panels.length; i++) {
                    id = panels[i].panel.filter('.hp-grid-panel').attr('id');
                    if (newPanelId && (id === newPanelId)) {
                        return true;
                    }
                }
                return false;
            }

            function createPanel(page, view, options) {
                var panel,
                panelElement = $(page);
                if (havePanel(panelElement)) {
                    return;
                }

                if (options) {
                    if (! options.priority) {
                        options.priority = DEFAULT_OPTIONS.priority--;
                    }
                }
                else {
                    options = {};
                    $.extend(options, DEFAULT_OPTIONS);
                    DEFAULT_OPTIONS.priorty--;
                }

                panelElement.filter('.hp-grid-panel').addClass('hp-grid-height-6');
                localizer.localizeDom(panelElement);

                panel =  {panel: panelElement, view: view, options:options};
                panels.push(panel);
                panels.sort(panelSortCompare);

                if (active) {
                    addPanelsToPage();
                    $(PANELS).hpGridPanels();
                } else {
                    // handle direct navigation to an expanded panel
                    addToSelector(panel);
                }
            }

            // panels need to be registered before init
            this.register = function(page, view, options) {
                createPanel(page, view, options);
            };


            this.init = function() {
                active = true;
                addPanelsToPage();
                $(PANELS).hpGridPanels();
            };

            this.pause = function() {
                active = false;
                $.each(panels, function (index, panel) {
                    if (panel.view.pause) {
                        panel.view.pause();
                    }
                });
            };

            this.resume = function() {
                active = true;
                addPanelsToPage();
                $.each(panels, function (index, panel) {
                    if (panel.view.resume) {
                        panel.view.resume();
                    }
                });
                $(PANELS).hpGridPanels('reset');
            };

        }

        return new SettingsOverviewView();

    }());

    return SettingsOverviewView;
});
