// (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',
    'text!hpsumpages/common/help.html',
    'hp/services/RESTXml',
    'hp/view/DialogView',
    'jquery',
    'hp/lib/jquery.hpTooltip'],
function (session, urlFragment, sidebar, Log, localizer, helpMenuHtml, helpHtml,  restapi, DialogView) {
    "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 ACTIVE = 'hp-active';
    var SELECTED = 'hp-selected';
    var WELCOME_PAGE = 'welcome';
    var ACTIVITY_PAGE = 'activity';

    var HelpMenu = (function () {

        var initialized = false;
        var banner = null;
        var contents = null;
        var productBook = null;
        var helpIndexFile = '/doc/help/' + session.getLanguage() + '/index.htm';

        // Options for downloading help topics xml from the server
        var uri = "/doc/help/topics.xml";
        var options = null;
        var type = "GET";
        var data;


        function HelpMenu() {

            /**
            * 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();
                }
            }

            this.init = function (bannerArg) {
            	
            	//IE8 throws an error for console object.. so this handles for IE8
            	if (window.console === undefined) {
					console = { log : function(){} };
				}

                if (!initialized) {
                    banner = bannerArg;
                    initialized = true;
                    contents = $(helpMenuHtml);
                    localizer.localizeDom(contents);
                    $(ACTIONS, contents).hide();
                    $(SCREENCASTS, contents).hide();

                    // Make help anchors target the help window
                    // NOTE: keep aligned with LinkTargetBuilder.makeLink()
                    $(CURRENT_ANCHOR, contents).attr('target', 'hphelp');
                     helpIndexFile = '/doc/help/' + session.getLanguage() + '/index.htm';
                    $(INDEX_ANCHOR, contents).attr('target', 'hphelp')
			    .attr('href', helpIndexFile);

                    $(FLYOUT, banner).append(contents);
                    $(CONTROL, banner).attr('tooltip',
                        localizer.getString('hpsum.common.help')).
                        hpTooltip();

                    $(CONTROL, banner).click(function (ev) {
                        if (!$(CONTROL).hasClass(SELECTED)) {
                            showSidebar();
                        } else {
                            hideSidebar(true);
                        }
                    });

                    sidebar.on('sidebarAdd', onSidebarAdd);
                    sidebar.on('sidebarRemove', onSidebarRemove);

                    // Get the help topics file from the server
                    getContextHelpXml();
					var guimode = session.getProperty("gui_mode");
					if(guimode == "offline_automatic" || guimode == "offline_interactive")
					{
						$('body').on('click',CURRENT_ANCHOR, openDialog);
						$('body').on('click',INDEX_ANCHOR, openDialog);
					}
                }
            };

			function openDialog(e)
			{
				var htmlContents = $(helpHtml);
				var height  = (($('body').height() * 90) / 100);

				$('iframe' ,$(htmlContents)).attr('src', $(this).attr('href'));

				var dialogView = new DialogView();
				dialogView.init({
					contents: htmlContents,
					ok: function () {
						return;
					},
					cancel: function () {
						return;
					},
					height: height + "px"
				});

				e.preventDefault();
			}
            // Following 3 API are to download help topics.xml file
            function getContextHelpXml() {

                var handlers = {
                    success: function (xml) {
                        //console.log("received xml response");
                        readXml(xml);
                    },
                    error: function (errorInfo) {
                        xmlReadFailed(errorInfo);
                    }
                };

                restapi.getURI(uri, handlers, options, data);
            }


            function readXml(xml) {
                if (xml) {
                    //console.log(xml);

                    $(xml).find("mapping").each(function () {
                        var id = $(this).attr("id");
                        var url = $(this).find("mapvalue").text();
                        var title = $(this).find("topictitle").text();

                        HelpMenu.htmlCache[id] = {
                            url: url,
                            title: title
                        };
                    });

                } else {
                    //console.log("data is undefined");
                }

            };

            function xmlReadFailed(errorInfo) {

                //console.log("xml get failed for /doc/topics.xml with error: " + errorInfo);
            }


            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>');
                }
                $(ACTIONS, contents).show();
            };

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

            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();
                $(SCREENCASTS + ' > ol', contents).
                    append('<li><a href="#' + location + '">' + label + '</a></li>');
                $(SCREENCASTS, contents).show();
            };

            this.setLocation = function (location) {
                var helpUrl;
                var htmlPage;

                var page = urlFragment.getPage(location);
                var viewList = urlFragment.getView(location).split("/");
                var view = viewList[0];

                var topicSearch;
                if (($.trim(page) === "") || (location.indexOf(WELCOME_PAGE) != -1)) {
                    topicSearch = WELCOME_PAGE;
                } else if (location.indexOf(ACTIVITY_PAGE) != -1) {
                    topicSearch = ACTIVITY_PAGE;
                } else if (view && view != "") {
                    topicSearch = page + "_" + view;
                }

                if (topicSearch in HelpMenu.htmlCache) {
                    htmlPage = HelpMenu.htmlCache[topicSearch].url;
                    //console.log("Found help page [" + htmlPage + "] for the location [" + location + "]");
                }

                if (htmlPage) {
                    helpUrl = '/doc/help/'+ session.getLanguage() + '/' + htmlPage;
                } else {
                    // Always default to home page if a context based file is unavailable
                    //console.log("No help file found for [" + location + "]. Setting context anchor to the main page.");
                    helpUrl = '/doc/help/' + session.getLanguage() + '/index.htm';
                }

                $(CURRENT_ANCHOR, contents).attr('href', helpUrl);
                // handle add/edit forms
                $(CURRENT_ANCHOR).attr('href', helpUrl).
                    attr('target', 'hphelp');

                var indexHelpUrl = '/doc/help/' + session.getLanguage() + '/index.htm' + '#hpsum_welcome_help' + '.htm';
                $(INDEX_ANCHOR, contents).attr('href', indexHelpUrl);
                $(INDEX_ANCHOR).attr('href', indexHelpUrl)
				.attr('target', 'hphelp');
            };

            this.setProductBook = function (book) {
                productBook = book;
            };
        }

        // Cache the HPSUM help topics data
        HelpMenu.htmlCache = {};

        return new HelpMenu();
    } ());

    return HelpMenu;
});
