'use strict';

var stringResources = require('./stringResources.js');
var pageCountLabel = require('./toolbar/page-count-label.js');
var pageNumberInput = require('./toolbar/page-number-input.js');
var constants = require('./constants.js');

function replaceStringResources($toolbar) {
  if (!$toolbar) {
    return;
  }
  const labels = $toolbar.find(".trv-replace-string");
  if (labels && labels.length > 0) {
    Array.from(labels).forEach((element) => {
      const $element = $(element);
      const stringResource = stringResources.stringResources[$element.text()];
      if ($element && stringResource) {
        $element.text(stringResource);
      }
    });
  }
}
class Toolbar {
  // #region fields
  _options;
  /** @type {HTMLElement} */
  _element;
  $element;
  _kendoToolbar;
  _neverOverflowToolBarButtons = ["goToPrevPage", "goToNextPage"];
  // #endregion
  // #region constructor
  constructor(element, options, viewerOptions) {
    this._element = element;
    this._options = options;
    this.$element = $(this._element);
    if (this._kendoToolbar === void 0) {
      this.initKendoToolbar();
    }
    this._options.controller.on("beginLoadReport", () => {
      const kendoExportDropDown = this.$element.find(`#${constants.ToolBarConstants.ExportDropdownId}`).data("kendoDropDownButton");
      kendoExportDropDown?.enable(false);
    }).onAsync("reportLoadComplete", async () => {
      if (viewerOptions.renderingExtensions === void 0) {
        this._options.controller.getDocumentFormats().then((extensions) => {
          this.updateExportDropdownItems(extensions);
        }).catch((error) => {
          this._options.controller.trigger("error", { message: error });
        });
      } else {
        this.updateExportDropdownItems(viewerOptions.renderingExtensions);
      }
    });
  }
  // #endregion
  // #region methods
  initKendoToolbar() {
    replaceStringResources(this.$element);
    const children = Array.from(this._element.children);
    const toolBarItems = [];
    children.forEach((child) => toolBarItems.push(this.createToolbarItem(child)));
    this.$element.empty();
    this._kendoToolbar = this.$element.kendoToolBar({
      items: toolBarItems,
      click: (e) => {
        this.executeCommand(e);
      },
      toggle: (e) => {
        this.executeCommand(e);
      }
    }).data("kendoToolBar");
    const pageNumberInputEl = this.$element.find(constants.ToolBarConstants.PageNumberInputDataRoleSelector).get(0);
    if (pageNumberInputEl) {
      new pageNumberInput.PageNumberInput(pageNumberInputEl, this._options);
    }
    const pageCountLabelEl = this.$element.find(constants.ToolBarConstants.PageCountLabelDataRoleSelector).get(0);
    if (pageCountLabelEl) {
      new pageCountLabel.PageCountLabel(pageCountLabelEl, this._options);
    }
  }
  createToolbarItem(elementData) {
    const cmdName = (elementData.dataset?.command || "").replace("telerik_ReportViewer_", "");
    if (cmdName === "toggleAiPromptDialog" && !this._options.controller.isAiInsightsEnabled()) {
      return;
    }
    const id = elementData.id;
    const role = elementData.dataset?.role;
    const icon = elementData.dataset?.icon;
    const overflow = elementData.dataset?.overflow;
    const title = stringResources.stringResources[elementData.title] || elementData.title || "";
    const ariaLabel = stringResources.stringResources[elementData.ariaLabel] || elementData.ariaLabel || "";
    const cmdParam = elementData.dataset?.commandParameter;
    const command = this._options.commands[cmdName];
    switch (role) {
      case constants.ToolBarConstants.Separator:
        return {
          type: constants.ToolBarConstants.Separator,
          overflow: overflow || "auto"
        };
      case constants.ToolBarConstants.CustomElement:
        elementData.title = title;
        elementData.ariaLabel = ariaLabel;
        return {
          template: elementData.outerHTML
        };
      case constants.ToolBarConstants.MenuButton:
        return {
          id,
          type: constants.ToolBarConstants.DropDownButton,
          icon,
          enable: false,
          showArrowButton: true,
          overflow: "never",
          fillMode: "flat",
          menuButtons: [
            { text: "Loading...", enabled: false }
          ]
        };
      case constants.ToolBarConstants.ButtonGroup:
        const groupChildren = Array.from(elementData.children);
        const buttonGroupButtons = [];
        groupChildren.forEach((groupChild) => {
          if (groupChild.dataset?.role !== constants.ToolBarConstants.Button && groupChild.dataset?.role !== constants.ToolBarConstants.ToggleButton) {
            console.warn("The data-role attribute of element nested inside a buttonGroup is missing or not supported. Only 'button' or 'toggle-button' data-role is allowed.");
            return;
          }
          buttonGroupButtons.push(this.createToolbarItem(groupChild));
        });
        return {
          type: constants.ToolBarConstants.ButtonGroup,
          buttons: buttonGroupButtons,
          fillMode: "flat",
          overflow: overflow ? overflow : "auto"
        };
      case constants.ToolBarConstants.Button:
      case constants.ToolBarConstants.ToggleButton:
        $(command).on("enabledChanged", (e, newState) => {
          this._kendoToolbar.enable($(`button[${constants.ToolBarConstants.DataCommandAttr}="${cmdName}"]`), newState);
        }).on("checkedChanged", (e, newState) => {
          this._kendoToolbar.toggle($(`button[${constants.ToolBarConstants.DataCommandAttr}="${cmdName}"]`), newState);
        });
        return {
          id,
          type: constants.ToolBarConstants.Button,
          text: title,
          icon,
          attributes: {
            [constants.ToolBarConstants.DataCommandAttr]: cmdName,
            [constants.ToolBarConstants.DataCommandParameterAttr]: cmdParam,
            [constants.ToolBarConstants.AriaLabelAttr]: ariaLabel,
            [constants.ToolBarConstants.TitleAttr]: title
          },
          fillMode: "flat",
          togglable: role === constants.ToolBarConstants.ToggleButton,
          overflow: overflow ? overflow : "auto",
          showText: "overflow"
        };
      default:
        console.error(`The data-role attribute is missing or not supported: ${role}`);
        return {};
    }
  }
  executeCommand(event) {
    const cmdName = event.target.get(0)?.dataset.command || "";
    const cmdParam = event.target.get(0)?.dataset.commandParameter || "";
    if (!cmdName) {
      return;
    }
    const cmdFn = this._options.commands[cmdName];
    if (!cmdFn) {
      console.error(`The provided data-command attribute is not present within the commands collection: ${cmdName}`);
      return;
    }
    cmdFn.exec(cmdParam);
  }
  updateExportDropdownItems(extensions) {
    const kendoExportDropDown = this.$element.find(`#${constants.ToolBarConstants.ExportDropdownId}`).data("kendoDropDownButton");
    if (!kendoExportDropDown) {
      return;
    }
    if (!(extensions && extensions.length > 0)) {
      console.warn("No extensions found - the export dropdown button will remain disabled.");
      return;
    }
    const exportDropdownItems = [];
    extensions.forEach((extension) => exportDropdownItems.push({
      id: extension.name,
      text: extension.localizedName,
      attributes: {
        [constants.ToolBarConstants.DataCommandAttr]: "export",
        [constants.ToolBarConstants.DataCommandParameterAttr]: extension.name
      }
    }));
    const options = kendoExportDropDown.options;
    options.items = exportDropdownItems;
    kendoExportDropDown.setOptions(options);
    kendoExportDropDown.enable(true);
  }
}

exports.Toolbar = Toolbar;
