'use strict';

var utils = require('./utils.js');
var stringResources = require('./stringResources.js');

function SideMenu(element, options, viewerOptions) {
  options = $.extend({}, options, viewerOptions);
  var menu = $(element).data("kendoMenu");
  var enableAccessibility = options.enableAccessibility;
  var DEFAULT_TABINDEX = 3;
  var panelBar;
  var sideMenuVisible = false;
  var controller = options.controller;
  var notificationService = options.notificationService;
  if (!controller) {
    throw "No controller (telerikReporting.ReportViewerController) has been specified.";
  }
  if (!notificationService) {
    throw "No notificationService (telerikReporting.NotificationService) has been specified.";
  }
  if (!menu) {
    init(element);
  }
  function init(root) {
    var $root = $(root);
    try {
      panelBar = $root.children("ul").kendoPanelBar().data("kendoPanelBar");
    } catch (e) {
      console.error("Instantiation of Kendo PanelBar as side menu threw an exception", e);
      throw e;
    }
    panelBar.bind("expand", onSubmenuOpen);
    panelBar.element.off("keydown", onPanelKeyDown);
    panelBar.element.on("keydown", onPanelKeyDown);
    setTabIndexes($root);
    enableCloseOnClick($root);
    $root.on("click", (e) => {
      if (e.target == root) {
        notificationService.setSideMenuVisible({ visible: !sideMenuVisible });
      }
    });
    replaceStringResources();
  }
  notificationService.setSideMenuVisible((event, args) => {
    setSideMenuVisibility();
    if (enableAccessibility) {
      panelBar.element.trigger("focus");
    }
    sideMenuVisible = args.visible;
    if (!sideMenuVisible) {
      panelBar.collapse($("#trv-side-menu-export-command"));
    }
  }).getSideMenuVisible((event, args) => {
    args.visible = sideMenuVisible;
  });
  function setSideMenuVisibility() {
    var $root = panelBar.element.parent();
    var hidden = $root.position().left < 0 || !$root.is(":visible");
    if (hidden) {
      $root.show();
    } else {
      window.setTimeout(() => {
        $root.hide();
      }, 500);
    }
  }
  function onSubmenuOpen(e) {
    var $item = $(e.item);
    panelBar.unbind("expand", onSubmenuOpen);
    panelBar.append({ text: stringResources.stringResources.loadingFormats, spriteCssClass: "k-icon k-loading" }, $item);
    options.controller.getDocumentFormats().then(fillFormats).then(() => {
      panelBar.expand($item);
    }).then(() => {
      panelBar.bind("expand", onSubmenuOpen);
    });
  }
  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 = $parent.attr("tabindex");
      if (!tabIndex) {
        tabIndex = DEFAULT_TABINDEX;
      }
      $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);
        panelBar.append(li, $parent);
      });
      setListItemsTabIndex($parent.find("li"), tabIndex);
      enableCloseOnClick($parent);
    });
  }
  function enableCloseOnClick(root) {
    Array.from(root.find("li")).forEach((listItem) => {
      var isLeaf = $(listItem).children("ul").length === 0;
      if (isLeaf) {
        $(listItem).children("a").on("click", (event) => {
          notificationService.setSideMenuVisible({ visible: !sideMenuVisible });
        });
      }
    });
  }
  function setTabIndexes(root) {
    if (!root) {
      return;
    }
    var $list = root.children("ul");
    var parentTabIndex = root.attr("tabindex");
    var listIndex = parentTabIndex ? parentTabIndex : DEFAULT_TABINDEX;
    setListItemsTabIndex($list, listIndex);
  }
  function setListItemsTabIndex(list, tabIndex) {
    list.attr("tabindex", tabIndex);
    var items = list.find("li");
    Array.from(items).forEach((item) => {
      var $item = $(item);
      $item.attr("tabindex", tabIndex);
      var anchor = $item.children("a");
      if (anchor.length > 0) {
        var $anchor = $(anchor);
        $anchor.attr("tabindex", -1);
      }
      $item.on("focus", (event) => {
        var anchor2 = $item.children("a");
        if (anchor2.length > 0) {
          anchor2.addClass("k-focus");
        }
      });
      $item.on("blur", (event) => {
        var anchor2 = $item.children("a");
        if (anchor2.length > 0) {
          anchor2.removeClass("k-focus");
        }
      });
      $item.off("keydown", onItemKeyDown);
      $item.on("keydown", onItemKeyDown);
    });
  }
  function onPanelKeyDown(e) {
    if (e.which == kendo.keys.ENTER) {
      var $item;
      var isSelectedFocusedItem = false;
      var focusedItem = document.activeElement;
      if (focusedItem && focusedItem.localName == "li") {
        var items = panelBar.element.find("li.k-item");
        for (var i = 0; i < items.length; i++) {
          var listItem = items[i];
          if (focusedItem === listItem) {
            $item = $(listItem);
            isSelectedFocusedItem = true;
            break;
          }
        }
      } else {
        $item = panelBar.select();
      }
      if (!$item || $item.length === 0) {
        return;
      }
      handleItemSelect($item, isSelectedFocusedItem);
    }
  }
  function onItemKeyDown(e) {
    if (e.which == kendo.keys.ENTER) {
      handleItemSelect($(e.target), false);
    }
  }
  function handleItemSelect(item, handleExpandCollapse) {
    if (item.length === 0) {
      return;
    }
    var isLeaf = item.children("ul").length === 0;
    if (!isLeaf) {
      if (handleExpandCollapse) {
        if (item.hasClass("k-active")) {
          panelBar.collapse(item);
        } else {
          panelBar.expand(item);
        }
      }
    } else {
      var $anchor = item.find("a");
      if ($anchor.length > 0) {
        $anchor[0].click();
      }
    }
  }
  function replaceStringResources() {
    var menuAreas = findMenuArea();
    if (!menuAreas) {
      return;
    }
    Array.from(menuAreas).forEach((menu2) => {
      var $menu = $(menu2);
      var menuItems = $menu.children("li.k-panelbar-header");
      $menu.attr("aria-label", stringResources.stringResources[$menu.attr("aria-label")]);
      Array.from(menuItems).forEach((menuItem) => {
        var $menuItem = $(menuItem);
        var $a = $menuItem.find("a");
        $menuItem.attr("aria-label", stringResources.stringResources[$menuItem.attr("aria-label")]);
        if ($a) {
          var $span = $a.find("span:not(.k-icon)");
          $a.attr("title", stringResources.stringResources[$a.attr("title")]);
          if ($span) {
            $span.text(stringResources.stringResources[$span.text()]);
          }
        }
      });
    });
  }
  function findMenuArea() {
    return $("div[data-role=telerik_ReportViewer_SideMenu] > ul");
  }
}

exports.SideMenu = SideMenu;
