'use strict';

const index$2 = require('./index-140bcbcd.js');
const index$4 = require('./index-bddf9814.js');
const App = require('./App-0b3e3f31.js');
require('./Token-8c5ba5d9.js');
const Item = require('./Item-00ce8c24.js');
const index = require('./index-ac98852d.js');
require('./Credentials-8e4749ab.js');
const index$1 = require('./index-d3079b93.js');
const index$3 = require('./index-dc498c54.js');
const unknown = require('./unknown-38d3748c.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 = unknown.Error.is(response) || typeof response == "string" ? OrderHandler.orders : response;
        if (OrderHandler.orders)
          OrderHandler.customerOrders = OrderHandler.orders.reduce((result, order) => {
            var _a;
            if ((index.Payment.Card.is(order.payment) || index.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 index$1.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) {
    index$2.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 index$3.Client.open((_a = this.server) !== null && _a !== void 0 ? _a : "", (_b = Item.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 index.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 = index$4.dist.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 && index.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 === Item.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;
      Item.Connection.key = merchant.value;
      this.updateMerchant();
      OrderHandler.download();
    }
  }
  async onSelectionChanged(e) {
    if (e.detail.identifier == "merchant") {
      this.orders = undefined;
      this.customers = undefined;
      Item.Connection.key = e.detail.value;
      this.updateMerchant();
      OrderHandler.download();
    }
  }
  render() {
    var _a, _b;
    const t = this.t;
    return (index$2.h("smoothly-notifier", null, index$2.h("portal-login", null, index$2.h(App.App, { label: "PayFunc Portal" }, Array.isArray((_a = this.user) === null || _a === void 0 ? void 0 : _a.merchant) ? (index$2.h("span", { slot: "header" }, index$2.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,
      })) }))) : (index$2.h("span", { slot: "header" }, this.merchant ? this.merchant.name : "")), index$2.h("smoothly-room", { path: "", to: this.default == "defer" ? "create" : "order" }), this.deferAllowed ? (index$2.h("smoothly-room", { label: t("Create"), path: "create" }, index$2.h("portal-defer-view", { emailOption: this.emailOption, currency: this.currency, orders: this.orders }))) : ([]), index$2.h("smoothly-room", { label: t("Orders"), path: "order" }, index$2.h("ig-orders", { orders: this.orders, receipt: this.whitelist() })), this.hasCustomers ? (index$2.h("smoothly-room", { label: t("Customers"), path: "customer" }, index$2.h("ig-customers", { client: PayfuncPortal.client, customers: this.customers, orders: this.customerOrders, whitelist: this.whitelist() }))) : ([]), this.hasSettlements ? (index$2.h("smoothly-room", { label: t("Settlements"), path: "settlement" }, index$2.h("ig-portal-settlements", { settlements: this.settlements, interchange: this.interchange }))) : ([]), index$2.h("smoothly-trigger", { slot: "nav-end", type: "link", name: "logout" }, index$2.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 index$2.getElement(this); }
};
PayfuncPortal.style = styleCss;

exports.OrderHandler = OrderHandler;
exports.PayfuncPortal = PayfuncPortal;
