'use strict';

var utils = require('./utils.js');
var stringResources = require('./stringResources.js');
var RCV = require('@progress/telerik-common-report-viewer');

var lastSelectedMenuItem;
var lastSelectedSubmenuItem;
function MainMenu(element, options, viewerOptions) {
  options = $.extend({}, options, viewerOptions);
  var menu = $(element).data("kendoMenu");
  var childrenL1 = element.childNodes;
  var controller = options.controller;
  var enableAccessibility = options.enableAccessibility;
  var lastKendoFocusedItem;
  var initialized = false;
  if (!controller) {
    throw "No controller (telerikReporting.ReportViewerController) has been specified.";
  }
  init();
  function init() {
    if (initialized) {
      return;
    }
    _initMenu();
    _attachEvents();
    replaceStringResources();
    if (options.enableAccessibility) {
      setTabIndexes();
    }
    initialized = true;
  }
  function _attachEvents() {
    controller.onAsync("reportLoadComplete", async (args) => {
      if (!enableAccessibility) {
        if (menu && menu._oldHoverItem) {
          menu._oldHoverItem.toggleClass("k-focus");
        }
      }
      if (!args.renderingExtensions) {
        controller.getDocumentFormats().then(fillFormats);
      } else {
        fillFormats(args.renderingExtensions);
      }
    });
  }
  function _initMenu() {
    try {
      menu = $(element).kendoMenu().data("kendoMenu");
    } catch (e) {
      console.error("Instantiation of Kendo Menu as Main Menu threw an exception", e);
      throw e;
    }
    menu.bind("activate", onSubmenuActivate);
    menu.bind("deactivate", onSubmenuDeactivate);
    menu.element.off("keydown", onMenuKeyDown);
    menu.element.on("keydown", onMenuKeyDown);
  }
  function setTabIndexes() {
    var $menus = $('[data-role="telerik_ReportViewer_MainMenu"]');
    Array.from($menus).forEach((menu2) => {
      var $menuArea = $(menu2);
      var listItems = $menuArea.find("li");
      var menuTabIndex = 0;
      var tabIndexAttr = $menuArea.attr("tabIndex");
      if (tabIndexAttr) {
        menuTabIndex = RCV.tryParseInt(tabIndexAttr);
        if (!menuTabIndex || isNaN(menuTabIndex)) {
          menuTabIndex = 0;
        }
      }
      setMenuItemsTabIndexes(listItems, menuTabIndex);
      var pager = listItems.find('input[data-role="telerik_ReportViewer_PageNumberInput"]');
      if (pager.length > 0) {
        pager.attr("tabindex", menuTabIndex);
      }
    });
  }
  function setMenuItemsTabIndexes(listItems, menuTabIndex) {
    Array.from(listItems).forEach((item) => {
      var $item = $(item);
      $item.attr("tabindex", menuTabIndex);
      $item.on("focus", (event) => {
        $item.addClass("k-focus");
      });
      $item.on("blur", (event) => {
        $item.removeClass("k-focus");
      });
      var anchor = $item.children("a");
      if (anchor.length > 0) {
        var $anchor = $(anchor);
        $anchor.attr("tabindex", -1);
        $item.attr("title", $anchor.attr("title"));
      }
      $item.off("keydown");
      $item.on("keydown", (event) => {
        if (event.which == kendo.keys.ENTER) {
          clickOnMenuItem($item);
          lastSelectedMenuItem = $item;
        }
      });
    });
  }
  function fillFormats(formats) {
    Array.from($(element).find("ul[data-command-list=export-format-list]")).forEach((list) => {
      var $list = $(list);
      var $parent = $list.parents("li");
      var tabIndex = enableAccessibility ? $parent.attr("tabindex") : -1;
      if (!tabIndex) {
        tabIndex = 1;
      }
      $list.empty();
      Array.from(formats).forEach((format) => {
        var ariaLabel = enableAccessibility ? utils.stringFormat('aria-label="{localizedName}" ', format) : " ";
        var li = "<li " + ariaLabel + utils.stringFormat('tabindex="' + tabIndex + '"><a tabindex="-1" href="#" data-command="telerik_ReportViewer_export" data-command-parameter="{name}"><span>{localizedName}</span></a></li>', format);
        menu.append(li, $parent);
      });
      if (enableAccessibility) {
        setInternalListAccessibilityKeyEvents($parent.find("li"));
      }
    });
  }
  function setInternalListAccessibilityKeyEvents(listItems) {
    Array.from(listItems).forEach((item) => {
      var $item = $(item);
      $item.off("keydown");
      $item.on("keydown", (event) => {
        switch (event.which) {
          case kendo.keys.ENTER:
            clickOnMenuItem($item);
            break;
          case kendo.keys.UP:
            var $prev = $item.prev();
            if ($prev.length > 0) {
              $prev.trigger("focus");
            } else {
              $item.parents("li").trigger("focus");
            }
            break;
          case kendo.keys.DOWN:
            var $next = $item.next();
            if ($next.length > 0) {
              $next.trigger("focus");
            } else {
              $item.parent().children("li").first().trigger("focus");
            }
            break;
        }
      });
    });
  }
  function clickOnMenuItem(item) {
    if (isItemExportContainer(item)) {
      clickOnExportDropdown();
    } else if (item && item.length > 0) {
      var anchor = item.children("a");
      if (anchor.length > 0) {
        anchor.click();
      }
    }
  }
  function clickOnExportDropdown() {
    var dropDownItemID = "#trv-main-menu-export-command";
    var mainMenu = $("[data-role='telerik_ReportViewer_MainMenu']").data("kendoMenu");
    mainMenu.open(dropDownItemID);
  }
  function onSubmenuActivate(e) {
    var $item = $(e.item);
    focusOnFirstSubmenuItem($item);
  }
  function onSubmenuDeactivate(e) {
    lastSelectedSubmenuItem = void 0;
  }
  function focusOnFirstSubmenuItem(parentItem) {
    if (lastSelectedMenuItem && lastSelectedMenuItem.is(parentItem)) {
      window.setTimeout(() => {
        var li = parentItem.find("li");
        if (li.length > 0) {
          li[0].focus();
        }
      }, 100);
    }
  }
  function onMenuKeyDown(e) {
    switch (e.which) {
      case kendo.keys.ENTER:
        if (!enableAccessibility) {
          var $item = getFocusedItem();
          if ($item.length > 0) {
            if (isItemExportContainer($item) && lastSelectedSubmenuItem) {
              $item = lastSelectedSubmenuItem;
            }
            clickOnMenuItem($item);
          }
        }
        break;
      case kendo.keys.RIGHT:
        enableAccessibility ? focusNextItemAccessibilitySelection() : focusNextItemNativeMenuSelection();
        break;
      case kendo.keys.LEFT:
        enableAccessibility ? focusPreviousItemAccessibilitySelection() : focusPreviousItemNativeMenuSelection();
        break;
      case kendo.keys.DOWN:
      case kendo.keys.UP:
        if (!enableAccessibility) {
          lastSelectedSubmenuItem = getKendoFocusedNestedItem();
        }
    }
  }
  function getFocusedItem() {
    var $item;
    var focusedItem = document.activeElement;
    if (focusedItem && focusedItem.localName == "li") {
      var items = $(childrenL1).filter("li.k-item");
      for (var i = 0; i < items.length; i++) {
        var listItem = items[i];
        if (focusedItem === listItem) {
          $item = $(listItem);
          break;
        }
      }
    } else if (focusedItem && focusedItem.localName == "input") {
      $item = $(focusedItem).closest("li.k-item");
    } else {
      $item = menu.element.children("li.k-item.k-focus");
      if ($item.length === 0) {
        $item = menu.element.children("li.k-item").first();
      }
    }
    return $item;
  }
  function focusNextItemAccessibilitySelection() {
    var $item = getFocusedItem();
    if (!$item || !$item.length > 0) {
      return;
    }
    var $next = $item.next();
    if ($next.css("display") == "none") {
      $next = $next.next();
    }
    if (!$next.length > 0) {
      $next = $(childrenL1).filter("li.k-item").first();
    }
    $next.focus();
  }
  function focusNextItemNativeMenuSelection() {
    var allItems = menu.element.children("li.k-item");
    var $focused = allItems.filter(".k-focus");
    if (kendo.version >= "2017.3.913") {
      lastKendoFocusedItem = $focused;
      return;
    }
    if ($focused.hasClass("k-disabled")) {
      if (!lastKendoFocusedItem || $focused.is(lastKendoFocusedItem)) {
        var $next = $focused.next();
        if (!$next.length > 0) {
          $next = allItems.first();
        }
        $focused.toggleClass("k-focus");
        $next.toggleClass("k-focus");
        lastKendoFocusedItem = $next;
        menu._oldHoverItem = $next;
      } else {
        lastKendoFocusedItem = $focused;
      }
    } else {
      menu._oldHoverItem = $focused;
      lastKendoFocusedItem = $focused;
    }
  }
  function focusPreviousItemAccessibilitySelection() {
    var $item = getFocusedItem();
    if (!$item || !$item.length > 0) {
      return;
    }
    var $prev = $item.prev();
    if ($prev.css("display") == "none") {
      $prev = $prev.prev();
    }
    if (!$prev.length > 0) {
      $prev = $(childrenL1).filter("li.k-item").last();
    }
    $prev.focus();
  }
  function focusPreviousItemNativeMenuSelection() {
    var $focused = menu.element.children("li.k-item.k-focus");
    lastKendoFocusedItem = $focused;
  }
  function getKendoFocusedNestedItem() {
    var $focused = menu.element.find('li.k-item.k-focus [data-command="telerik_ReportViewer_export"]');
    if ($focused.length === 1) {
      return $focused.parent("li");
    }
    return void 0;
  }
  function isItemExportContainer(item) {
    if (item.length === 0) {
      return;
    }
    var id = item.attr("id");
    return id == "trv-main-menu-export-command" || id == "trv-side-menu-export-command";
  }
  function replaceStringResources() {
    var menuAreas = findMenuArea();
    if (!menuAreas) {
      return;
    }
    Array.from(menuAreas).forEach((menu2) => {
      var $menu = $(menu2);
      var menuItems = $menu.children("li.k-item");
      $menu.attr("aria-label", stringResources.stringResources[$menu.attr("aria-label")]);
      Array.from(menuItems).forEach((menuItem) => {
        var $menuItem = $(menuItem);
        $menuItem.attr("aria-label", stringResources.stringResources[$menuItem.attr("aria-label")]);
        if (!$menuItem.hasClass("trv-report-pager")) {
          var $a = $menuItem.find("a");
          if ($a) {
            $a.attr("title", stringResources.stringResources[$a.attr("title")]);
          }
        } else {
          $menuItem.attr("title", stringResources.stringResources[$menuItem.attr("title")]);
        }
      });
    });
  }
  function findMenuArea() {
    return $("ul[data-role=telerik_ReportViewer_MainMenu]");
  }
}

exports.MainMenu = MainMenu;
