import { Component, Element, h, Listen, Prop, State } from "@stencil/core";
import { Currency } from "isoly";
import { App } from "smoothly";
import { Key, Settlement } from "@payfunc/model";
import { Connection } from "@payfunc/model-base";
import { Client } from "@payfunc/merchant-client";
import { OrderHandler } from "./OrderHandler";
import * as translation from "./translation";
export class PayfuncPortal {
  constructor() {
    this.deferAllowed = false;
    this.hasCustomers = false;
    this.hasSettlements = false;
    this.default = "order";
    this.emailOption = false;
    this.customerOrders = {};
  }
  async componentWillLoad() {
    var _a, _b;
    this.t = translation.create(this.element);
    if (!this.server)
      document.querySelectorAll("script").forEach(element => {
        if (typeof element === "object" &&
          typeof element.src === "string" &&
          (element.src.endsWith("payfunc-portal.js") || element.src.endsWith("payfunc-portal.esm.js"))) {
          const origin = new URL(element.src).origin;
          this.server = origin + "/";
        }
      });
    PayfuncPortal.client = await Client.open((_a = this.server) !== null && _a !== void 0 ? _a : "", (_b = Connection.key) !== null && _b !== void 0 ? _b : "", "me", "order", "customer");
    this.handleOnUserChanged();
  }
  async handleOnUserChanged(e) {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const user = (_a = e === null || e === void 0 ? void 0 : e.detail.user) !== null && _a !== void 0 ? _a : (_b = PayfuncPortal.client) === null || _b === void 0 ? void 0 : _b.me.user;
    this.user = user;
    if (user) {
      this.interchange = ((_c = user === null || user === void 0 ? void 0 : user.option) === null || _c === void 0 ? void 0 : _c.interchange) ? user.option.interchange : undefined;
      const merchant = Array.isArray(user.merchant) ? user.merchant[0] : user.merchant;
      const merchantKey = merchant ? await Key.unpack(merchant.key.private, "private") : undefined;
      this.deferAllowed = ((_d = merchantKey === null || merchantKey === void 0 ? void 0 : merchantKey.features) === null || _d === void 0 ? void 0 : _d.deferAllowed) ? true : false;
      this.hasCustomers =
        !!merchantKey && ["testtest", "demodemo", "BUeG1Dl0", "exMLQZY5", "vkHDPN0D"].includes(merchantKey.sub);
      this.hasSettlements =
        !!merchantKey &&
          (["testtest", "demodemo"].includes(merchantKey.sub) ||
            !!((_e = user === null || user === void 0 ? void 0 : user.option) === null || _e === void 0 ? void 0 : _e.settlement) ||
            !!((_g = (_f = merchantKey === null || merchantKey === void 0 ? void 0 : merchantKey.card) === null || _f === void 0 ? void 0 : _f.mid) === null || _g === void 0 ? void 0 : _g.startsWith("8103")));
      this.emailOption = ((_h = merchantKey === null || merchantKey === void 0 ? void 0 : merchantKey.features) === null || _h === void 0 ? void 0 : _h.emailOption) ? true : false;
      this.currency = Currency.is(merchantKey === null || merchantKey === void 0 ? void 0 : merchantKey.currency) ? merchantKey === null || merchantKey === void 0 ? void 0 : merchantKey.currency : "SEK";
      if (user && user.option && user.option.portal && user.option.portal.startView)
        this.default =
          user.option.portal.startView == "order" || (user.option.portal.startView == "defer" && this.deferAllowed)
            ? user.option.portal.startView
            : "order";
    }
    this.loadData();
    this.updateMerchant();
  }
  loadData() {
    OrderHandler.register((client, orders, customerOrders) => {
      var _a;
      this.orders = orders;
      this.settlements = (_a = this.settlements) !== null && _a !== void 0 ? _a : (this.orders && Settlement.generate(this.orders));
      this.customerOrders = customerOrders;
    }, PayfuncPortal.client);
    if (this.hasCustomers)
      this.loadCustomers();
  }
  updateMerchant() {
    var _a;
    const merchant = (_a = this.user) === null || _a === void 0 ? void 0 : _a.merchant;
    this.merchant = Array.isArray(merchant) ? merchant.find(m => m.key.private === Connection.key) : merchant;
  }
  async handleTrigger(event) {
    var _a;
    if (event.detail.name == "logout") {
      event.stopPropagation();
      event.preventDefault();
      (_a = PayfuncPortal.client) === null || _a === void 0 ? void 0 : _a.me.logout();
      this.user = undefined;
      location.reload();
    }
  }
  async handleUpdateOrder(event) {
    event ? (this.orders = [...event.detail]) : OrderHandler.download();
  }
  async loadCustomers(event) {
    var _a;
    this.customers = event
      ? [...event.detail].reverse()
      : (await ((_a = PayfuncPortal.client) === null || _a === void 0 ? void 0 : _a.customer.list())).reverse();
  }
  async handleMenuClose(e) {
    var _a;
    const merchant = Array.isArray(e.detail) ? e.detail[0] : e.detail;
    if (merchant.descripion != ((_a = this.merchant) === null || _a === void 0 ? void 0 : _a.id)) {
      this.orders = undefined;
      this.customers = undefined;
      Connection.key = merchant.value;
      this.updateMerchant();
      OrderHandler.download();
    }
  }
  async onSelectionChanged(e) {
    if (e.detail.identifier == "merchant") {
      this.orders = undefined;
      this.customers = undefined;
      Connection.key = e.detail.value;
      this.updateMerchant();
      OrderHandler.download();
    }
  }
  render() {
    var _a, _b;
    const t = this.t;
    return (h("smoothly-notifier", null,
      h("portal-login", null,
        h(App, { label: "PayFunc Portal" },
          Array.isArray((_a = this.user) === null || _a === void 0 ? void 0 : _a.merchant) ? (h("span", { slot: "header" },
            h("smoothly-picker", { label: this.t("Select Merchant"), "max-height": "58px", style: { width: "500px" }, options: (_b = this.user) === null || _b === void 0 ? void 0 : _b.merchant.map(m => ({
                name: m.name,
                value: m.key.private,
                description: m.id,
              })) }))) : (h("span", { slot: "header" }, this.merchant ? this.merchant.name : "")),
          h("smoothly-room", { path: "", to: this.default == "defer" ? "create" : "order" }),
          this.deferAllowed ? (h("smoothly-room", { label: t("Create"), path: "create" },
            h("portal-defer-view", { emailOption: this.emailOption, currency: this.currency, orders: this.orders }))) : ([]),
          h("smoothly-room", { label: t("Orders"), path: "order" },
            h("ig-orders", { orders: this.orders, receipt: this.whitelist() })),
          this.hasCustomers ? (h("smoothly-room", { label: t("Customers"), path: "customer" },
            h("ig-customers", { client: PayfuncPortal.client, customers: this.customers, orders: this.customerOrders, whitelist: this.whitelist() }))) : ([]),
          this.hasSettlements ? (h("smoothly-room", { label: t("Settlements"), path: "settlement" },
            h("ig-portal-settlements", { settlements: this.settlements, interchange: this.interchange }))) : ([]),
          h("smoothly-trigger", { slot: "nav-end", type: "link", name: "logout" },
            h("smoothly-icon", { toolTip: t("Log out"), name: "log-out", size: "medium" }))))));
  }
  whitelist() {
    var _a, _b;
    return !!((_a = this.merchant) === null || _a === void 0 ? void 0 : _a.id) && ["testtest", "demodemo", "test0123"].includes((_b = this.merchant) === null || _b === void 0 ? void 0 : _b.id);
  }
  static get is() { return "payfunc-portal"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() { return {
    "$": ["style.css"]
  }; }
  static get styleUrls() { return {
    "$": ["style.css"]
  }; }
  static get properties() { return {
    "server": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string | undefined",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "server",
      "reflect": false
    }
  }; }
  static get states() { return {
    "t": {},
    "deferAllowed": {},
    "hasCustomers": {},
    "hasSettlements": {},
    "default": {},
    "emailOption": {},
    "currency": {},
    "orders": {},
    "customers": {},
    "customerOrders": {},
    "merchant": {},
    "settlements": {},
    "interchange": {},
    "user": {}
  }; }
  static get elementRef() { return "element"; }
  static get listeners() { return [{
      "name": "userChanged",
      "method": "handleOnUserChanged",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "trigger",
      "method": "handleTrigger",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "updateOrder",
      "method": "handleUpdateOrder",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "updateCustomers",
      "method": "loadCustomers",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "menuClose",
      "method": "handleMenuClose",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "selectionChanged",
      "method": "onSelectionChanged",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
