// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @constructor
 * @type {SearchView}
 */
define(['hp/presenter/SearchPresenter',
    'hp/presenter/AssociatedRoute',
    'hp/view/SearchBoxView',
    'hp/core/LinkTargetBuilder',
    'hp/core/NotificationFormatter',
    'hp/core/StatusState',
    'hp/core/Localizer',
    'hp/services/Log',
    'jquery', 'hp/lib/jquery.hpStatus'],
function(presenter, associatedRoute, searchBoxView, linkTargetBuilder,
    notificationFormatter, statusState, localizer, log) {"use strict";

    var SearchView = ( function() {

        var RESULTS = '#hp-search-results tbody';
        var TEMPLATE = '#hp-search-result-template';
        var CONTROLS_TEMPLATE = '#hp-search-controls-template';
        var SPINNER = '#hp-search-spinner';
        var EMPTY = '#hp-search-page .hp-empty-message';
        var COUNT = '.hp-page-item-count';
        var TYPE = '.hp-search-type';
        var STATUS = '.hp-status';
        var NAME = '.hp-search-name';
        var MATCHES = '.hp-search-matches';
        var LOADMORE_SPINNER = '<div class="hp-spinner-small"><div class="hp-spinner-image"></div></div>';

        /**
         * @constructor
         * @type {SearchView}
         */
        function SearchView() {

            var template;
            var controlsTemplate;
            var selectSearchText = true;

            function updateSummary(count) {
                $(COUNT).text(count);
            }

            /**
             * Removes the "Load more" row at the end.
             */
            function removeControls() {
                $(RESULTS + ' .hp-search-table-controls').remove();
            }

            /**
             * Adds the "show more" row at the end.
             */
            function addControls() {
                $(RESULTS).append(controlsTemplate.clone());
            }
            
            function addResult(indexResult, query) {
                var result = template.clone();
                var link;
                var name = indexResult.name ? indexResult.name : indexResult.description;
                
                name = notificationFormatter.collapseInlineLinks(name);

                link = linkTargetBuilder.makeLink(name, indexResult.uri, null,
                    indexResult.category, null, null, null, ['f_q=' + query]);
                $(TYPE, result).text(linkTargetBuilder.categoryLabel(indexResult.category));
                $(NAME, result).html(link);
                if (indexResult.status) {
                    var status = statusState.getHealthStatus(indexResult.status);
                    $(STATUS, result).hpStatus(status);
                }
                var matches = presenter.resultMatches(indexResult);
                var length = matches.length;
                for (var i=0; i<length; i++) {
                    var match = matches[i];
                    var li = $('<li></li>');
                    var matchName = $('<span></span>').addClass('hp-name').text(match[0]);
                    li.append(matchName);
                    var matchValue = $('<span></span>').addClass('hp-value').text(match[1]);
                    li.append(matchValue);
                    $(MATCHES, result).append(li);
                }

                $(RESULTS).append(result);
            }
            
            function onClickShowMore(ev) {
                var tableCell = $(ev.target).parent();
                tableCell.empty().append(LOADMORE_SPINNER);
                presenter.searchMore();
            }
            
            function onClickAssociated(event) {
                var elem = $(event.currentTarget);
                associatedRoute.routeToAssociated(elem.attr('data-assoc-name'),
                    elem.attr('data-assoc-uri'));
            }

            function onIndexResultsChange(indexResults) {
                var query = presenter.getQuery();
            
                if (indexResults.start === 0) {
                    // new search
                    removeControls();
                    $(RESULTS).empty();
                    searchBoxView.setGlobalSearchText(query);
                    searchBoxView.activate(selectSearchText);
                }

                removeControls();
                
                $.each(indexResults.members, function(index, indexResult) {
                    addResult(indexResult, query);
                });

                if (presenter.hasMoreResult()) {
                    addControls();
                }
                
                updateSummary(indexResults.total);
                // only select search text when we first come to this page
                selectSearchText = false;
                
                $(EMPTY).toggle(indexResults.total === 0);
            }

            /**
             * @public
             */
            this.init = function() {
                $(SPINNER).hide(); // not needed?
                template = $(TEMPLATE).removeAttr('id').removeClass('hp-template');
                $(RESULTS).detach(TEMPLATE);
                controlsTemplate = $(CONTROLS_TEMPLATE).removeAttr('id').removeClass('hp-template');
                $(RESULTS).detach(CONTROLS_TEMPLATE);

                $(RESULTS).on('click', 'a.hp-search-show-more', onClickShowMore);
                $(RESULTS).on('click', 'tr', function (event) {
                    if (! $(event.target).is('a')) {
                        $('.hp-search-name a', this).click();
                    }
                });
                $(RESULTS).on('click', 'a[data-assoc-uri]', onClickAssociated);
                presenter.init();
                this.resume();
            };

            /**
             * @public
             */
            this.pause = function() {
                 $(COUNT).text('');
            };

            /**
             * @public
             */
            this.resume = function() {
                selectSearchText = true;
                document.title = localizer.getString('search.title');
                presenter.on('indexResultsChange', onIndexResultsChange);                  
            };
        }

        return new SearchView();
    }());

    return SearchView;
});
