'use strict';

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

class PageNumberInput extends baseComponent.BaseComponent {
  // #region fields
  cmd;
  _numeric;
  // #endregion
  // #region constructor
  constructor(element, options) {
    super(element, options);
    this.cmd = this.options.commands["goToPage"];
    this._numeric = new kendo.ui.NumericTextBox(this.element, {
      format: "0",
      decimals: 0,
      min: 0,
      spinners: false,
      change: this._onChange.bind(this),
      spin: this._onChange.bind(this)
    });
    this._numeric._text[0].dataset.role = "telerik_ReportViewer_PageNumberInput";
    this._numeric.element[0].dataset.role = "";
    this._numeric.wrapper[0].classList.add("trv-toolbar-numeric");
    this._numeric._text[0].setAttribute("aria-label", stringResources.stringResources.ariaLabelPageNumberEditor);
    this.options.controller.onAsync("reportLoadComplete", async (reportInfo) => {
      this._numeric.max(reportInfo.pageCount);
      this._numeric.min(Math.min(1, reportInfo.pageCount));
      this._numeric.value(Math.min(1, reportInfo.pageCount));
    }).on("loadedReportChange", () => {
      this._numeric.min(0);
      this._numeric.max(0);
      this._numeric.value(0);
    }).on("renderingStopped", () => {
      this._numeric.min(0);
      this._numeric.max(0);
      this._numeric.value(0);
    });
    this.options.notificationService.pageNumberChange((event, value) => {
      var pageNumber = value;
      var pageCount = this.options.controller.getPageCount();
      this.element.parentElement.setAttribute("aria-label", utils.stringFormat(stringResources.stringResources.ariaLabelPageNumberSelector, [pageNumber, pageCount]));
      this._numeric.value(value);
    });
  }
  // #endregion
  // #region event handlers
  _onChange(event, data) {
    var val = this._numeric.value();
    var num = RCV.tryParseInt(val);
    if (!isNaN(num)) {
      this.cmd.exec(num);
    }
  }
  _onSpin(event, data) {
    return this._onChange(event, data);
  }
  // #endregion
}

exports.PageNumberInput = PageNumberInput;
