'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index$1 = require('./index-140bcbcd.js');
const unknown = require('./unknown-38d3748c.js');
const Token = require('./Token-8c5ba5d9.js');
const index$2 = require('./index-ac98852d.js');
const App = require('./App-0b3e3f31.js');
const Item = require('./Item-00ce8c24.js');
require('./Credentials-8e4749ab.js');
const index = require('./index-d3079b93.js');
const Handler = require('./Handler-51fdca63.js');
require('./_commonjsHelpers-537d719a.js');
require('./index-09251373.js');
require('./TextDecoder-753156f3.js');
require('./index-dc498c54.js');

function isDefined(value) {
  return value != undefined;
}

const sv = {
  "Your link is invalid or expired. Please check your email for a new link.": "Din länk är ogiltig eller har upphört att gälla. En ny länk har skickats till din mail.",
  subscription: "prenumeration",
  methods: "metoder",
  address: "adress",
  balance: "saldo",
  "Customer ID": "Kund ID",
};

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

const styleCss = "h1.errorMessage.sc-intergiro-customer{padding-left:1.4em;padding-top:3em}[component=\"app\"].sc-intergiro-customer-h{min-width:60em;min-height:calc(40em);width:auto;height:auto;display:inline-block}[component].sc-intergiro-customer-h header.sc-intergiro-customer{position:relative}[component].sc-intergiro-customer-h content.sc-intergiro-customer{top:0cm}[component].sc-intergiro-customer-h header.sc-intergiro-customer>*.sc-intergiro-customer:nth-child(2){display:none}[component].sc-intergiro-customer-h header.sc-intergiro-customer nav.sc-intergiro-customer ul.sc-intergiro-customer li.sc-intergiro-customer:last-child{display:none}.sc-intergiro-customer-h{font-family:var(--smoothly-font-family)}";

const IntergiroCustomer = class {
  constructor(hostRef) {
    index$1.registerInstance(this, hostRef);
    this.notice = index$1.createEvent(this, "notice", 7);
    this.login = false;
    this.paths = [""];
    this.unpackedKeys = [];
  }
  async componentWillLoad() {
    await Handler.Handler.open("", "");
    Handler.Handler.client.me.onUnauthorized = () => {
      this.customer = undefined;
      return Promise.reject();
    };
    if (location.search && location.search.split("&").length > 2) {
      const queryParameters = location.search.substring(1).split("&");
      const customerId = decodeURIComponent(queryParameters[0].split("=")[1]);
      const linkId = decodeURIComponent(queryParameters[1].split("=")[1]);
      if (Token.Identifier.is(customerId, 16) && Token.Identifier.is(linkId, 16)) {
        Item.Connection.key = "a.b.c";
        Item.Connection.url = decodeURIComponent(queryParameters[2].split("=")[1]);
        await Handler.Handler.client.customer.openLink(customerId, linkId);
      }
    }
    this.authenticate();
    this.t = create(this.element);
  }
  async authenticate() {
    var _a;
    this.apiKey && this.apiKey != "" && (Item.Connection.key = this.apiKey);
    const unpackedKey = await index$2.Key.getVerifier().verify(Item.Connection.key, "customer");
    if (unpackedKey && unpackedKey.customer && Item.Connection.key) {
      this.login = false;
      Handler.Handler.client.me.addCustomerKey((_a = Item.Connection.key) !== null && _a !== void 0 ? _a : "", unpackedKey.customer);
      Item.Connection.url = unpackedKey.iss;
      const response = await Handler.Handler.client.customer.get("me");
      this.unpackedKeys = await Handler.Handler.client.me.customerKeys.reduce(async (accumulator, currentKey) => {
        const unpacked = await index$2.Key.getVerifier()
          .add(index$2.Remover.create(["exp"]))
          .verify(currentKey, "customer");
        if (unpacked)
          (await accumulator).push(unpacked);
        return accumulator;
      }, Promise.resolve([]));
      this.customer = !unknown.Error.is(response) && typeof response != "string" ? response : undefined;
      this.unpackedKey = unpackedKey;
      const orders = await Handler.Handler.client.order.list();
      this.customerRefresh = window.setTimeout(async () => {
        await this.getCustomer();
      }, 30000);
      if (!unknown.Error.is(orders) && typeof orders != "string")
        this.orders = orders;
    }
    else {
      window.clearTimeout(this.customerRefresh);
      this.customerRefresh = undefined;
      if (!this.unpackedKey)
        this.login = true;
    }
    this.features();
  }
  async onSelectionChanged(e) {
    if (e.detail.identifier == "customer") {
      this.apiKey = e.detail.value;
      this.authenticate();
    }
  }
  async updateMethod(event) {
    if (index$2.Customer.is(this.customer)) {
      await Handler.Handler.client.customer.setMethods(this.customer.method, "me");
      await Handler.Handler.client.customer.retryPayment();
      await this.getCustomer();
    }
  }
  async getCustomer() {
    const response = await Handler.Handler.client.customer.get("me");
    if (!unknown.Error.is(response))
      this.customer = response;
    return response;
  }
  logIn(e) {
    this.apiKey = e.detail[0];
    this.unpackedKey = e.detail[1];
    this.login = false;
    this.authenticate();
  }
  features() {
    var _a;
    this.paths =
      ((_a = this.unpackedKey) === null || _a === void 0 ? void 0 : _a.features) == undefined
        ? this.paths
        : [
          "",
          this.checkAccess(this.unpackedKey.features, "customer.order", true),
          this.checkAccess(this.unpackedKey.features, "customer.subscription", false),
          this.checkAccess(this.unpackedKey.features, "customer.balance", false),
          this.checkAccess(this.unpackedKey.features, "customer.address", true),
          this.checkAccess(this.unpackedKey.features, "customer.method", true),
        ].filter(isDefined);
  }
  checkAccess(features, flag, showByDefault) {
    return flag.match(/\w+\.\w+/)
      ? this.checkAccess(features[flag.split(".")[0]], flag.split(".")[1], showByDefault)
      : (features != undefined && typeof features[flag] == "boolean" ? features[flag] : showByDefault)
        ? flag
        : undefined;
  }
  handleTrigger(event) {
    if (event.detail.name == "logout") {
      this.login = true;
      this.apiKey = undefined;
      this.customer = undefined;
      Item.Connection.key = undefined;
    }
  }
  getCustomCssVariables() {
    var _a, _b, _c, _d, _e;
    const result = {};
    if (this.cosmetic && (typeof this.cosmetic == "object" || ((_a = this.cosmetic) === null || _a === void 0 ? void 0 : _a.length) > 0)) {
      const cosmetic = typeof this.cosmetic == "string" && this.cosmetic.length > 0 ? JSON.parse(this.cosmetic) : this.cosmetic;
      Object.entries({
        "--smoothly-font-family": (_b = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.fontFamily) !== null && _b !== void 0 ? _b : cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.font_family,
        "--smoothly-primary-color": (_c = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.success) === null || _c === void 0 ? void 0 : _c.background,
        "--smoothly-success-color": (_d = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.success) === null || _d === void 0 ? void 0 : _d.background,
        "--smoothly-success-contrast": (_e = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.success) === null || _e === void 0 ? void 0 : _e.color,
      }).forEach(([key, value]) => {
        value && (result[key] = value);
      });
    }
    return result;
  }
  render() {
    const t = this.t;
    return (index$1.h(index$1.Host, { style: this.getCustomCssVariables() }, !this.component || this.component == "app" ? (index$1.h("customer-login", { open: this.login, onSelected: e => this.logIn(e) }, index$1.h(App.App, { label: "Intergiro Customer" }, index$2.Customer.is(this.customer)
      ? [
        index$1.h("smoothly-room", { path: "", to: "" }),
        this.unpackedKeys.length > 1 ? (index$1.h("smoothly-select", { slot: "header", identifier: "customer", background: "transparent" }, this.unpackedKeys.map(a => {
          var _a;
          return (index$1.h("option", { value: a.token, selected: ((_a = this.unpackedKey) === null || _a === void 0 ? void 0 : _a.customer) == a.customer }, `${a.name} - ${t("Customer ID")}: ${a.customer}`));
        }))) : (index$1.h("span", { slot: "header" }, this.unpackedKey ? this.unpackedKey.name : "")),
        this.paths.includes("order") && (index$1.h("smoothly-room", { label: t("order"), path: "order" }, index$1.h("customer-orders", { orders: this.orders, cosmetic: this.cosmetic, receipt: this.whitelistReceipt(), component: this.component }))),
        this.paths.includes("subscription") && (index$1.h("smoothly-room", { label: t("subscription"), path: "subscription" }, index$1.h("customer-subscriptions", { customer: this.customer, cosmetic: this.cosmetic, orders: this.orders, receipt: this.whitelistReceipt(), component: this.component }))),
        this.paths.includes("balance") && (index$1.h("smoothly-room", { label: t("balance"), path: "balance" }, index$1.h("customer-balance", { customer: this.customer, orders: this.orders, component: this.component }))),
        this.paths.includes("method") && (index$1.h("smoothly-room", { label: t("methods"), path: "method" }, index$1.h("customer-methods", { "api-key": Item.Connection.key, cosmetic: this.cosmetic, customer: this.customer, methods: this.customer.method, onUpdate: (e) => this.updateMethod(e), component: this.component }))),
        this.paths.includes("address") && (index$1.h("smoothly-room", { label: t("address"), path: "address" }, index$1.h("customer-address", { customer: this.customer, component: this.component }))),
      ]
      : [
        this.paths.map(path => (index$1.h("smoothly-room", { path: path }, index$1.h("customer-error", { component: this.component, unpackedKey: this.unpackedKey })))),
      ], index$1.h("smoothly-trigger", { slot: "nav-end", type: "link", fill: "clear", name: "logout" }, index$1.h("smoothly-icon", { toolTip: "Log out", name: "log-out", size: "medium", fill: "clear", color: "light" }))))) : !index$2.Customer.is(this.customer) ? (index$1.h("customer-error", { component: this.component, unpackedKey: this.unpackedKey })) : this.component == "order" && this.paths.includes("order") ? (index$1.h("customer-orders", { orders: this.orders, cosmetic: this.cosmetic, receipt: this.whitelistReceipt(), component: this.component })) : this.component == "subscription" && this.paths.includes("subscription") ? (index$1.h("customer-subscriptions", { customer: this.customer, cosmetic: this.cosmetic, orders: this.orders, receipt: this.whitelistReceipt(), component: this.component })) : this.component == "balance" && this.paths.includes("balance") ? (index$1.h("customer-balance", { customer: this.customer, orders: this.orders, component: this.component })) : this.component == "method" && this.paths.includes("method") ? (index$1.h("customer-methods", { cosmetic: this.cosmetic, customer: this.customer, methods: this.customer.method, onUpdate: (e) => this.updateMethod(e), component: this.component })) : this.component == "address" && this.paths.includes("address") ? (index$1.h("customer-address", { customer: this.customer, component: this.component })) : (index$1.h("customer-error", { component: this.component, unpackedKey: this.unpackedKey }))));
  }
  whitelistReceipt() {
    var _a, _b;
    return ((_a = this.unpackedKey) === null || _a === void 0 ? void 0 : _a.sub) != undefined && ["testtest", "test0123"].includes((_b = this.unpackedKey) === null || _b === void 0 ? void 0 : _b.sub);
  }
  get element() { return index$1.getElement(this); }
};
IntergiroCustomer.style = styleCss;

exports.intergiro_customer = IntergiroCustomer;
