import { r as registerInstance, h, g as getElement } from './index-08b73e9e.js';
import { d as dist$1 } from './index-3cf720d3.js';
import { A as App } from './App-364e27cc.js';
import './Token-ba2c5d5c.js';
import { a as Connection } from './Item-f4cbd6f4.js';
import { a as Payment, K as Key, S as Settlement } from './index-3299c1c0.js';
import './Credentials-b84c0c5f.js';
import { d as dist } from './index-a0a71287.js';
import { C as Client } from './index-26d778c4.js';
import { E as Error } from './unknown-97022c22.js';

class OrderHandler {
  static async register(callback, client) {
    this.client = client;
    this.callbacks.push(callback);
    callback(this.client, this.orders, this.customerOrders);
    if (!OrderHandler.timer) {
      this.download();
      OrderHandler.timer = setInterval(OrderHandler.download, 5000);
    }
  }
  static async download() {
    var _a;
    if (!this.downloading) {
      try {
        this.downloading = true;
        const response = await ((_a = OrderHandler.client) === null || _a === void 0 ? void 0 : _a.order.list());
        this.downloading = false;
        OrderHandler.orders = Error.is(response) || typeof response == "string" ? OrderHandler.orders : response;
        if (OrderHandler.orders)
          OrderHandler.customerOrders = OrderHandler.orders.reduce((result, order) => {
            var _a;
            if ((Payment.Card.is(order.payment) || Payment.Customer.is(order.payment)) &&
              (order.payment.customer || order.customer))
              ((_a = result[typeof order.payment.customer == "string"
                ? order.payment.customer
                : typeof order.customer == "string"
                  ? order.customer
                  : ""]) !== null && _a !== void 0 ? _a : (result[typeof order.payment.customer == "string"
                ? order.payment.customer
                : typeof order.customer == "string"
                  ? order.customer
                  : ""] = [])).push(order);
            return result;
          }, {});
        OrderHandler.callbacks.forEach(callback => callback(OrderHandler.client, OrderHandler.orders, OrderHandler.customerOrders));
      }
      catch (_b) {
        this.downloading = false;
      }
    }
  }
}
OrderHandler.downloading = false;
OrderHandler.customerOrders = {};
OrderHandler.callbacks = [];

const sv = {
  Create: "Skapa",
  Orders: "Ordrar",
  Customers: "Kunder",
  "Failed to cancel order.": "Misslyckades avbryta order.",
  "Log out": "Logga ut",
  Settlements: "Utbetalningar",
};

function create(language) {
  return dist.create({
    sv,
  }, language);
}

const styleCss = ".sc-payfunc-portal-h{display:block}[hidden].sc-payfunc-portal-h{display:none}header.sc-payfunc-portal{z-index:2}@media screen and (max-width: 499px){.sc-payfunc-portal-h>portal-login.sc-payfunc-portal>smoothly-app.sc-payfunc-portal>smoothly-notifier.sc-payfunc-portal>header.sc-payfunc-portal>span.sc-payfunc-portal{display:none}}";

const PayfuncPortal = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.deferAllowed = false;
    this.hasCustomers = false;
    this.hasSettlements = false;
    this.default = "order";
    this.emailOption = false;
    this.customerOrders = {};
  }
  async componentWillLoad() {
    var _a, _b;
    this.t = 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 = dist$1.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);
  }
  get element() { return getElement(this); }
};
PayfuncPortal.style = styleCss;

export { OrderHandler as O, PayfuncPortal as P };
