// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {HelpMenu}
 */
define(['hp/model/Session',
    'hp/core/UrlFragment',
    'hp/core/Sidebar',
    'hp/services/Log',
    'hp/core/Localizer',
    'text!hpPages/core/help_menu.html',
    'jquery',
    'hp/lib/jquery.hpTooltip'],
function (session, urlFragment, sidebar, Log, localizer, helpMenuHtml) { "use strict";

    var CONTROL = '#hp-help-control';
    var FLYOUT = '#hp-help-flyout';
    var CURRENT_ANCHOR = '.hp-help-current';
    var INDEX_ANCHOR = '.hp-help-index';
    var ACTIONS = '#hp-help-actions';
    var ACTION = ACTIONS + ' a';
    var SCREENCASTS = '#hp-help-screencasts';
    var SCREENCAST = SCREENCASTS + ' a';
    var DOCUMENTATION = '#hp-help-documentation';
    var DOCUMENT = DOCUMENTATION + ' a';
    var COMMUNITIES = '#hp-help-communities';
    var COMMUNITY = COMMUNITIES + ' a';
    var BODY = '#hp-body-div';
    var ACTIVE = 'hp-active';
    var SIDEBARRED = 'hp-sidebarred';
    var SELECTED = 'hp-selected';
    var UNAVAILABLE = 'hp-unavailable';
    var WRITTEN_OFFER_LINK = "#hp-help-writtenoffer";
    var EULA_LINK = "#hp-help-eula";

    var HelpMenu = (function () {

        var initialized = false;
        var contents = null;
        var productBook = null;
        var activateOnResume = false;
        
        function HelpMenu() {
          
            function resetSection(section, anchors) {
                var show = ($(anchors).not('.' + UNAVAILABLE).length > 0);
                $(section).toggle(show);
            }
          
            function resetSections() {
                var simple = ($(FLYOUT).parents('#hp-simple-banner').length > 0);
                $(ACTION).not('.' + UNAVAILABLE).toggleClass(UNAVAILABLE, simple);
                if (!simple) {
                    $('#hp-help-local-offline', contents).hide();
                }
                // if any sections are empty, hide them
                resetSection(ACTIONS, ACTION);
                resetSection(SCREENCASTS, SCREENCAST);
                resetSection(DOCUMENTATION, DOCUMENT);
                resetSection(COMMUNITIES, COMMUNITY);
            }
          
            /**
             * Completely hide flyout.
             */
            function hideSidebar(remove) {
                if ($(FLYOUT).hasClass(ACTIVE)) {
                    $(FLYOUT).removeClass(ACTIVE);
                    $(CONTROL).removeClass(SELECTED);
                    if (remove) {
                        sidebar.remove($(FLYOUT));
                    }
                }
            }
            
            /**
             * Put the flyout into the sidebar.
             */
            function showSidebar() {
                if (! $(FLYOUT).hasClass(ACTIVE)) {
                    $(FLYOUT).addClass(ACTIVE);
                    $(CONTROL).addClass(SELECTED);
                    sidebar.add($(FLYOUT));
                }
            }
            
            function onSidebarRemove(element) {
                if (element.attr('id') === $(FLYOUT).attr('id')) {
                    hideSidebar();
                }
            }
            
            function onSidebarAdd(element) {
                if (element.attr('id') === $(FLYOUT).attr('id')) {
                    showSidebar();
                }
            }
            
            function hideFlyout() {
                $(BODY).unbind('click', hideFlyout);
                $(FLYOUT).css('top', - $(FLYOUT).outerHeight());
                $(FLYOUT).removeClass(ACTIVE);
                $(CONTROL).removeClass(SELECTED);
            }
            
            function showFlyout() {
                $(FLYOUT).css('top', '');
                $(FLYOUT).addClass(ACTIVE);
                $(CONTROL).addClass(SELECTED);
                // delay to avoid flickering
                setTimeout(function () {$(BODY).bind('click', hideFlyout);}, 50);
            }
            
            function createListItemAnchor(label, location) {
                var item = $('<li></li>');
                item.append($('<a></a>').attr('href', location).text(label));
                return item;
            }

			// this function hides the writtenoffer link in help menu
            // for partners who doesnt have written offer
            function onLoadSupportSuccess(data, status, xhr) {
                var writtenOfferHtml = $(data).filter('#hp-eula-partner-content');
                writtenOfferHtml = $.trim(writtenOfferHtml.text());
                var lengthStr = writtenOfferHtml.length;
                if (lengthStr !== 0) {
                    $(WRITTEN_OFFER_LINK, contents).show();
                }else{
                    $(WRITTEN_OFFER_LINK, contents).hide();
                    $().hide();
                }
            }

            function onLoadSupportError(jqXHR, textStats, errorThrown) {
                $(WRITTEN_OFFER_LINK).hide();
            }

            function checkToDisplayWrittenOfferLink() {
               var url = localizer.getString('fs.settings.eula.config.content_directory') + "/" +
                   localizer.getString('fs.settings.eula.config.support_access_file');
               $.ajax({
                   url: url,
                   type: 'GET',
                   async: true,
                   dataType: "html",
                   success: onLoadSupportSuccess,
                   error: onLoadSupportError
               });
            }

            function saveCurrentURI() {
                var tmpCurrentURI = window.location.href;
                var storedURI = session.getProperty("currentURI");
                if (tmpCurrentURI.indexOf("#") > 0 && storedURI == null) {
                    var currentURI = tmpCurrentURI.substring(tmpCurrentURI.indexOf("#")+1, tmpCurrentURI.length);
                    session.setProperty("currentURI", currentURI, false);
                }
            }
            
            this.init = function (banner, simpleBanner) {

                if (! initialized) {
                    initialized = true;
                    contents = $(helpMenuHtml);
                    localizer.localizeDom(contents);
                    //function to check if writtenofferlink to be displayed
                    checkToDisplayWrittenOfferLink();
                    // Make help anchors target the help window
                    // NOTE: keep aligned with LinkTargetBuilder.makeLink()
                    $(CURRENT_ANCHOR, contents).attr('target', 'hphelp');
                    $(INDEX_ANCHOR, contents).attr('target', 'hphelp')
                        .attr('href', '/doc#/' + (productBook ? productBook : ''));
                    
                    $(CONTROL, banner).attr('tooltip',
                        localizer.getString('core.help.control.tooltip')).
                        hpTooltip();
                    $(CONTROL, simpleBanner).attr('tooltip',
                        localizer.getString('core.help.control.tooltip')).
                        hpTooltip();

                    $(banner).on('click', CONTROL, function (ev) {
                        if (!$(CONTROL).hasClass(SELECTED)) {
                            showSidebar();
                        } else {
                            hideSidebar(true);
                        }
                    });
                    
                    $(simpleBanner).on('click', CONTROL, function (ev) {
                        if (!$(CONTROL).hasClass(SELECTED)) {
                            showFlyout();
                        } else {
                            hideFlyout();
                        }
                    });
                    
                    // onclick of eula/writtenoffer store the current uri in session
                    // after displaying eula/writtenoffer, on close button click in change page container
                    // redirect the page to current user page
                    
                    $(WRITTEN_OFFER_LINK, contents).click(function (ev) {
                        saveCurrentURI();
                    });
                    $(EULA_LINK, contents).click(function (ev) {
                        saveCurrentURI();
                    });

                    sidebar.on('sidebarAdd', onSidebarAdd);
                    sidebar.on('sidebarRemove', onSidebarRemove);
                    
                    resetSections();
                }
            };
            
            this.pin = function () {
                showSidebar();
            };
            
            this.unpin = function () {
                hideSidebar(true);
            };

            this.addAction = function (label, location) {
                this.init();
                if (location.substring(0,4) === 'doc#') {
                    $(ACTIONS + ' > ol', contents).
                        append('<li><a href="' + location + '" target="hphelp">' +
                            label + '</a></li>');
                }
                else {
                    $(ACTIONS + ' > ol', contents).
                        append('<li><a href="#' + location + '">' + label + '</a></li>');
                }
                resetSections();
            };
            
            this.removeAction = function (location) {
                $(ACTION + '[href$="' + location + '"]', contents).
                    parent().remove();
                if ($('.hp-done', contents).length === 0) {
                    $(ACTIONS).removeClass('hp-has-indicators');
                }
                resetSections();
            };
            
            this.updateActionLabel = function (label, location) {
                $(ACTION + '[href$="' + location + '"]', contents).
                    html(label);
            };

            this.markActionDone = function (location) {
                $(ACTIONS, contents).addClass('hp-has-indicators');
                $(ACTION + '[href$="' + location + '"]', contents).
                    parent().addClass('hp-done');
            };
            
            this.markActionNotDone = function (location) {
                $(ACTION + '[href$="' + location + '"]', contents).
                    parent().removeClass('hp-done');
                if ($('.hp-done', contents).length === 0) {
                    $(ACTIONS).removeClass('hp-has-indicators');
                }
            };

            this.addScreencast = function (label, location) {
                this.init();
                var item = createListItemAnchor(label, location);
                $(SCREENCASTS + ' > ol', contents).append(item);
                resetSections();
            };
            
            this.addCommunity = function (label, location) {
                this.init();
                var item = createListItemAnchor(label, location);
                $('a', item).attr('target', '_blank');
                $(COMMUNITIES + ' > ol', contents).append(item);
                resetSections();
            };

            this.addDocumentation = function (label, location) {
                this.init();
                var item = createListItemAnchor(label, location);
                $('a', item).attr('target', 'hphelp');
                $(DOCUMENTATION + ' > ol', contents).append(item);
                resetSections();
            };
            
            this.setLocation = function (location) {
                var helpUrl;
                // update help link
                helpUrl = '/doc#/' + (productBook ? productBook + '/' : '') +
                    urlFragment.getPage(location) +
                    '/' + urlFragment.getView(location);
                $(CURRENT_ANCHOR, contents).attr('href', helpUrl);
                // handle add/edit forms
                $(CURRENT_ANCHOR).attr('href', helpUrl).
                    attr('target', 'hphelp');
            };
            
            this.setProductBook = function(book) {
                productBook = book;
            };
            
            this.getProductBook = function() {
                return productBook;
            };
            
            // For use only by Banner
            this.pause = function () {
                var active = $(FLYOUT).hasClass(ACTIVE);
                var sidebarred = $(FLYOUT).hasClass(SIDEBARRED);
                if (active) {
                    if (sidebarred) {
                        hideSidebar(true);
                    } else {
                        hideFlyout();
                    }
                }
                activateOnResume = active;
                contents.detach();
            };
            
            this.resume = function (isMainBanner) {
                $(FLYOUT).append(contents);
                $('a', contents).removeClass(UNAVAILABLE);
                resetSections();
                
                if (activateOnResume) {
                    if (isMainBanner) {
                        showSidebar();
                    } else {
                        showFlyout();
                    }
                }
            };

            // For use only by status
            this.allowLocal = function (enabled) {
                $('a', contents).not('[href^="http"]').toggleClass(UNAVAILABLE, !enabled);
                $('#hp-help-local-offline', contents).toggle(!enabled);
                resetSections();
            };
        }

        return new HelpMenu();
    }());

    return HelpMenu;
});
