import { h } from "@stencil/core";
import { watchBlockNumber } from "@wagmi/core";
import { MDCSelect } from "@material/select";
import { handleError } from "../../utils/errors";
import state from "../../stores/wallet";
export class NKEditionMintButton {
  constructor() {
    this.select = null;
    this.disabled = true;
    this.loading = true;
    this.quantity = undefined;
    this.maxQuantity = undefined;
    this.maxPerWallet = undefined;
    this.maxPerMint = undefined;
    this.price = undefined;
    this.active = undefined;
    this.selections = [];
    this.dialogOpen = false;
    this.selectedValue = -1;
    this.editionId = undefined;
    this.successTitle = 'Success';
    this.successMessage = 'Successfully minted an NFT';
  }
  componentWillLoad() {
    this.disconnect = watchBlockNumber({ listen: true }, async () => {
      const [edition, price] = await Promise.all([
        state.diamond.apps.edition.getEdition(this.editionId),
        state.diamond.apps.edition.getEditionPrice(this.editionId),
      ]);
      const { quantity, maxQuantity, maxPerWallet, maxPerMint, active } = edition;
      this.quantity = quantity.toNumber();
      this.maxQuantity = maxQuantity.toNumber();
      this.maxPerWallet = maxPerWallet.toNumber();
      this.maxPerMint = maxPerMint.toNumber();
      this.price = price;
      this.active = active;
      this.selections = Array(this.maxPerMint).fill('');
      this.loading = false;
      // sale not active then disable widget
      this.disabled = !this.active;
    });
  }
  componentDidLoad() {
    this.setSelectedText();
  }
  componentDidUpdate() {
    if (this.selections.length > 0 && !this.select) {
      this.select = new MDCSelect(this.container);
      this.select.listen('MDCSelect:change', () => {
        // trigger mint
        this.selectedValue = Number(this.select.value);
        this.mint(this.selectedValue);
      });
    }
    this.setSelectedText();
  }
  disconnectedCallback() {
    this.disconnect();
  }
  async mint(quantity) {
    var _a, _b;
    try {
      this.loading = true;
      const { address, connector } = state.client.getAccount();
      const chainId = await connector.getChainId();
      if (chainId !== ((_a = state.chain) === null || _a === void 0 ? void 0 : _a.id)) {
        state.modal.openModal({
          route: 'SelectNetwork',
        });
        return;
      }
      if (this.active) {
        const verify = await state.diamond.verifyForEdition(address, this.editionId);
        const tx = await state.diamond.apps.edition.mintEdition(address, this.editionId, quantity, (_b = verify === null || verify === void 0 ? void 0 : verify.proof) !== null && _b !== void 0 ? _b : [], {
          value: this.price.mul(quantity),
        });
        await tx.wait();
        this.dialogTitle = this.successTitle;
        this.dialogMessage = this.successMessage;
        this.dialogOpen = true;
        return;
      }
      throw new Error('Sale is not active.');
    }
    catch (err) {
      console.log(err);
      this.dialogTitle = 'Error';
      this.dialogMessage = handleError(err);
      this.dialogOpen = true;
    }
    finally {
      this.loading = false;
    }
  }
  setSelectedText() {
    setTimeout(() => {
      const result = this.selectedValue < 0 ? '<slot />' : this.selectedValue.toString();
      this.selectedText.innerHTML = this.loading ? '<nk-loading />' : result;
    }, 10);
  }
  optionClasses(value) {
    return `mdc-deprecated-list-item ${this.selectedValue === value ? 'mdc-deprecated-list-item--selected' : ''}`;
  }
  render() {
    return (h("div", { part: "mint-btn-container", class: `mdc-select mdc-select--filled mdc-select--no-label ${this.disabled ? 'mdc-select--disabled' : ''}`, ref: (el) => (this.container = el) }, h("div", { part: "mint-btn", class: "mdc-select__anchor", role: "button", "aria-haspopup": "listbox", "aria-expanded": "false", "aria-labelledby": "mint-selected-text" }, h("span", { class: "mdc-select__ripple" }), h("span", { class: "mdc-select__selected-text-container" }, h("span", { part: "mint-text", id: "mint-selected-text", class: "mdc-select__selected-text", ref: (el) => (this.selectedText = el) })), h("span", { part: "mint-dropdown-icon", class: "mdc-select__dropdown-icon" }, h("svg", { class: "mdc-select__dropdown-icon-graphic", viewBox: "7 10 10 5", focusable: "false" }, h("polygon", { class: "mdc-select__dropdown-icon-inactive", stroke: "none", "fill-rule": "evenodd", points: "7 10 12 15 17 10" }), h("polygon", { class: "mdc-select__dropdown-icon-active", stroke: "none", "fill-rule": "evenodd", points: "7 15 12 10 17 15" })))), h("div", { class: "mdc-select__menu mdc-menu mdc-menu-surface mdc-menu-surface--fullwidth" }, h("ul", { class: "mdc-deprecated-list", role: "listbox", "aria-label": "Quantity Picker listbox" }, this.selections.map((_, value) => (h("li", { class: this.optionClasses(value + 1), "aria-selected": value + 1 === this.selectedValue, "data-value": value + 1, role: "option" }, h("span", { class: "mdc-deprecated-list-item__ripple" }), h("span", { class: "mdc-deprecated-list-item__text" }, value + 1)))))), h("nk-dialog", { open: this.dialogOpen, dialogTitle: this.dialogTitle }, this.dialogMessage)));
  }
  static get is() { return "nk-edition-mint-button"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["nk-edition-mint-button.scss"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["nk-edition-mint-button.css"]
    };
  }
  static get properties() {
    return {
      "editionId": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": true,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Edition ID"
        },
        "attribute": "edition-id",
        "reflect": false
      },
      "successTitle": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Title on the success modal"
        },
        "attribute": "success-title",
        "reflect": false,
        "defaultValue": "'Success'"
      },
      "successMessage": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Body message on the success modal"
        },
        "attribute": "success-message",
        "reflect": false,
        "defaultValue": "'Successfully minted an NFT'"
      }
    };
  }
  static get states() {
    return {
      "disabled": {},
      "loading": {},
      "quantity": {},
      "maxQuantity": {},
      "maxPerWallet": {},
      "maxPerMint": {},
      "price": {},
      "active": {},
      "selections": {},
      "dialogOpen": {},
      "selectedValue": {}
    };
  }
  static get methods() {
    return {
      "mint": {
        "complexType": {
          "signature": "(quantity: number) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
}
//# sourceMappingURL=nk-edition-mint-button.js.map
