import { h, Host } from "@stencil/core";
import { PrintUtils } from "../../lib/utils/PrintUtils";
import { ApplicationUtils } from "@sankhyalabs/ezui/dist/collection/utils";
import { ApplicationContext, ElementIDUtils } from "@sankhyalabs/core";
import ModalButtonStatus from "@sankhyalabs/ezui/dist/collection/components/ez-modal-container/modal-button-status";
export class SnkPrintSelector {
  constructor() {
    this.APPLY = "OK";
    this.CANCEL = "CANCEL";
    this.CLOSE = "CLOSE";
    this.REMOTE_PRINTERS_TAB = '0';
    this.LOCAL_PRINTERS_TAB = '1';
    this._hasRemotePrinters = false;
    this._hasLocalPrinters = false;
    this._localPrinters = [];
    this._isSingleJob = false;
    this._saveSubstitute = false;
    this.buildIdTabSelector = () => {
      const defaultTabs = [
        {
          label: this.getMessage("snkPrintSelector.title.localPrintersTab"),
          tabKey: this.LOCAL_PRINTERS_TAB,
          index: Number(this.LOCAL_PRINTERS_TAB)
        }
      ];
      if (this._printServerActive) {
        defaultTabs.unshift({
          label: this.getMessage("snkPrintSelector.title.remotePrintersTab"),
          tabKey: this.REMOTE_PRINTERS_TAB,
          index: Number(this.REMOTE_PRINTERS_TAB)
        });
      }
      return [...defaultTabs];
    };
    this._printServerActive = false;
    this._selectedPrinter = undefined;
    this._remotePrintersDataSource = [];
    this._localPrintersDataSource = [];
    this._printJobData = undefined;
  }
  async openPrintSelector(printJobData) {
    return new Promise((resolve) => {
      this._printJobData = printJobData;
      this._isSingleJob = this._printJobData.pendingPrinters.length === 1;
      this._printServerActive = this._printJobData.printServerActive;
      if (this._printServerActive) {
        this.buildRemotePrinters();
      }
      else {
        this.buildLocalPrinters();
        this._viewStack.show(+this.LOCAL_PRINTERS_TAB);
      }
      this._ezPopup.opened = true;
      this._printerResolver = resolve;
    });
  }
  closePrintSelector() {
    this._ezPopup.opened = false;
    this.element.remove();
  }
  handleModalAction(evt) {
    switch (evt) {
      case this.APPLY:
        this.handleApply();
        break;
      case this.CANCEL:
      case this.CLOSE:
        this.handleCancel();
        break;
    }
  }
  async handleCancel() {
    const result = await ApplicationUtils.confirm(this.getMessage("snkPrintSelector.title.warning"), this.getMessage("snkPrintSelector.message.canceledPrint"));
    if (result) {
      this.closePrintSelector();
      this._printerResolver({ selectedPrinter: undefined, saveSubstitute: false });
    }
  }
  handleApply() {
    this._printerResolver({ selectedPrinter: this._selectedPrinter, saveSubstitute: this._saveSubstitute });
    this.closePrintSelector();
  }
  onChangeTab(evt) {
    if (evt.detail.tabKey === this.LOCAL_PRINTERS_TAB) {
      this.buildLocalPrinters();
    }
    this._viewStack.show(+evt.detail.tabKey);
  }
  buildRemotePrinters() {
    const dataSource = [];
    this._printJobData.printServers.forEach((printServer) => {
      dataSource.push({
        group: printServer.printServerUri,
        items: printServer.printerList.map((printer) => ({
          label: printer.printerName,
          group: printServer.printServerUri
        }))
      });
    });
    this._remotePrintersDataSource = dataSource;
    this._hasRemotePrinters = this._remotePrintersDataSource.length > 0;
  }
  buildLocalPrinters() {
    if (this._localPrintersDataSource.length > 0)
      return;
    this._localPrinters = PrintUtils.getInstance().getLocalPrinters();
    this._localPrintersDataSource = this._localPrinters.map((printer) => ({
      label: printer.nome
    }));
    this._hasLocalPrinters = this._localPrintersDataSource.length > 0;
  }
  onSelectPrinter(printer, isLocal) {
    if (isLocal) {
      if (this._hasRemotePrinters)
        this._remotePrintersList.removeSelection();
      this._selectedPrinter = this._localPrinters.find((item) => item.nome === printer.label);
      return;
    }
    if (this._hasLocalPrinters)
      this._localPrintersList.removeSelection();
    const serverGroup = this._printJobData.printServers.find((item) => item.printServerUri === printer.group);
    this._selectedPrinter = serverGroup === null || serverGroup === void 0 ? void 0 : serverGroup.printerList.find((item) => item.printerName === printer.label);
  }
  renderNoPrinters() {
    return (h("div", { class: 'ez-flex ez-flex--justify-center ez-flex--align-items-center ez-size-height--full ez-size-width--full' }, h("span", { class: 'ez-text ez-text--primary ez-text--medium' }, this.getMessage("snkPrintSelector.message.noPrinters"))));
  }
  buildPrinterIcon() {
    return (h("ez-icon", { iconName: "print", style: { marginRight: 'var(--space--small)' } }));
  }
  getElementID(sufix) {
    return {
      [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(sufix)
    };
  }
  getMessage(path) {
    return this._application.messagesBuilder.getMessage(path, undefined);
  }
  componentWillLoad() {
    this._application = ApplicationContext.getContextValue("__SNK__APPLICATION__");
  }
  componentDidLoad() {
    if (!this.element)
      return;
    ElementIDUtils.addIDInfo(this.element);
  }
  render() {
    return (h(Host, null, h("ez-popup", Object.assign({ size: 'small', heightMode: 'full', useHeader: false, ref: (ref) => this._ezPopup = ref }, this.getElementID("snk-print-selector")), h("ez-modal-container", { modalTitle: this.getMessage("snkPrintSelector.title.printerSelection"), okButtonLabel: this.getMessage("snkPrintSelector.button.print"), okButtonStatus: this._selectedPrinter ? ModalButtonStatus.ENABLED : ModalButtonStatus.DISABLED, cancelButtonLabel: this.getMessage("snkPrintSelector.button.cancel"), onEzModalAction: (evt) => this.handleModalAction(evt.detail) }, this._isSingleJob &&
      h("div", { class: 'ez-flex ez-margin-bottom--large' }, h("div", { class: 'ez-flex ez-margin-right--large' }, h("span", { class: 'ez-text ez-text--bold ez-text--medium ez-padding-right--small' }, this.getMessage("snkPrintSelector.subtitle.document")), h("span", { class: 'ez-text ez-text--primary ez-text--medium' }, this._printJobData.pendingPrinters[0].docTypeDescription)), h("div", { class: 'ez-flex ez-margin-right--large' }, h("span", { class: 'ez-text ez-text--bold ez-text--medium ez-padding-right--small' }, this.getMessage("snkPrintSelector.subtitle.jobs")), h("span", { class: 'ez-text ez-text--primary ez-text--medium' }, this._printJobData.pendingPrinters[0].printJobCount))), h("ez-tabselector", { tabs: this.buildIdTabSelector(), onEzChange: (evt) => this.onChangeTab(evt), selectedTab: this._printServerActive ? this.REMOTE_PRINTERS_TAB : this.LOCAL_PRINTERS_TAB }), h("ez-view-stack", { ref: (ref) => this._viewStack = ref }, h("stack-item", { hidePolicy: 'hide' }, this._printServerActive &&
      h("div", { class: `list-scroll ez-size-height--full ${this._isSingleJob ? 'with-header' : 'without-header'}` }, h("ez-list", { ref: (ref) => this._remotePrintersList = ref, class: `ez-padding-top--medium ${this._hasRemotePrinters ? '' : 'hidden'}`, dataSource: this._remotePrintersDataSource, onEzSelectItem: (evt) => this.onSelectPrinter(evt.detail, false), itemLeftSlotBuilder: this.buildPrinterIcon, useGroups: true, ezSelectable: true, hoverFeedback: true, "data-element-id": 'remotePrintersList' }), !this._hasRemotePrinters && this.renderNoPrinters())), h("stack-item", { hidePolicy: 'hide' }, h("div", { class: `list-scroll ez-size-height--full ${this._isSingleJob ? 'with-header' : 'without-header'}` }, h("ez-list", { ref: (ref) => this._localPrintersList = ref, class: `ez-padding-top--medium ${this._hasLocalPrinters ? '' : 'hidden'}`, dataSource: this._localPrintersDataSource, onEzSelectItem: (evt) => this.onSelectPrinter(evt.detail, true), itemLeftSlotBuilder: this.buildPrinterIcon, ezSelectable: true, hoverFeedback: true }), !this._hasLocalPrinters && this.renderNoPrinters()))), h("ez-check", { label: this.getMessage("snkPrintSelector.message.savePrinter"), onEzChange: evt => this._saveSubstitute = evt.detail })))));
  }
  static get is() { return "snk-print-selector"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() {
    return {
      "$": ["snk-print-selector.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["snk-print-selector.css"]
    };
  }
  static get states() {
    return {
      "_printServerActive": {},
      "_selectedPrinter": {},
      "_remotePrintersDataSource": {},
      "_localPrintersDataSource": {},
      "_printJobData": {}
    };
  }
  static get methods() {
    return {
      "openPrintSelector": {
        "complexType": {
          "signature": "(printJobData: PendingPrintJobData) => Promise<PrintSelectorResponse>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "PrintSelectorResponse": {
              "location": "local"
            },
            "PendingPrintJobData": {
              "location": "import",
              "path": "../../lib/utils/PrintUtils"
            }
          },
          "return": "Promise<PrintSelectorResponse>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "element"; }
}
